Say I have the following method inside a UIViewController
subclass:
- (void)makeAsyncNetworkCall
{
[self.networkService performAsyncNetworkCallWithCompletion:^{
dispatch_async(dispatch_get_main_queue(), ^{
[self.activityIndicatorView stopAnimating];
}
});
}];
}
I know that the reference to self
inside the block results in the UIViewController
instance being retained by the block. As long as performAsyncNetworkCallWithCompletion
does not store the block in a property (or ivar) on my NetworkService
, am I right in thinking there is no retain cycle?
I realise this structure above will lead to the UIViewController being retained until performAsyncNetworkCallWithCompletion
finishes, even if it is released by the system earlier. But is it likely (or even possible?) the system will deallocate my UIViewController
at all (after the changes to the way iOS 6 manages a UIViewController
's backing CALayer
memory)?
If there is a reason I must do the "weakSelf/strongSelf dance", it would look like this:
- (void)makeAsyncNetworkCall
{
__weak typeof(self) weakSelf = self;
[self.networkService performAsyncNetworkCallWithCompletion:^{
typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
[strongSelf.activityIndicatorView stopAnimating];
}
});
}];
}
But I find this unconscionably ugly and would like to avoid it if it's not necessary.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…