From 4b2c2818a182a9427113580395366bf6b697c1c7 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 31 Oct 2012 07:49:44 -0700 Subject: [PATCH] Using conventional weak/strong self pattern to break retain cycle in background tasks --- AFNetworking/AFURLConnectionOperation.m | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 69b0473..2ddd7c5 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -257,16 +257,20 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat [self.lock lock]; if (!self.backgroundTaskIdentifier) { UIApplication *application = [UIApplication sharedApplication]; - __unsafe_unretained typeof(self) _blockSelf = self; + __weak __typeof(&*self)weakSelf = self; self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ + __strong __typeof(&*weakSelf)strongSelf = weakSelf; + if (handler) { handler(); } - [_blockSelf cancel]; - - [application endBackgroundTask:_blockSelf.backgroundTaskIdentifier]; - _blockSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; + if (strongSelf) { + [strongSelf cancel]; + + [application endBackgroundTask:strongSelf.backgroundTaskIdentifier]; + strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; + } }]; } [self.lock unlock];