Block中的weakSelf和StrongSelf
2016-06-16 本文已影响122人
Mossion
在看SVProgressHUD源码时,看到里面的StrongSelf时我是拒绝的:
// Define blocks
__weak SVProgressHUD *weakSelf = self;
__block void (^animationsBlock)(void) = ^{
__strong SVProgressHUD *strongSelf = weakSelf;
if(strongSelf) {
// Shrink HUD to finish pop up animation
strongSelf.hudView.transform = CGAffineTransformScale(strongSelf.hudView.transform, 1/1.3f, 1/1.3f);
strongSelf.alpha = 1.0f;
strongSelf.hudView.alpha = 1.0f;
}
};
在官方文档中,苹果是建议用__weakSelf解决循环引用的问题的,但是在下列情况下,weakSelf不一定会得到释放:
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
__strong __typeof(self) strongSelf = weakSelf;
[strongSelf doSomething];
[strongSelf doOtherThing];
});
在doSomething中,weakSelf不会变成nil,但是在doSomething执行完后,weakSelf就可能变成nil,这时候就可能引发问题了,而StrongSelf则能完美解决。StrongSelf确保在Block中,StrongSelf不会被释放。