使用Block何时需要WeakSelf和StrongSelf

作者: JackTheBest | 来源:发表于2016-12-04 20:41 被阅读182次

在使用 block 的时候,为了避免产生循环引用,通常需要使用 weakSelf 与 strongSelf,写下面这样的代码:

__weak typeof(self) weakSelf = self;
[self doSomeBackgroundJob:^{
  __strong typeof(weakself) strongSelf = weakself;
  if (strongself) {
    ...
  }
}];
  • 为什么要使用weakself?

比如上面code,如果不使用weakself 会引起循环的问题(retain circle),self持有block,block持有self。

  • 为什么要使用strongself?
__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];
});

__strong 确保在 Block 内,strongSelf 不会被释放。在执行期间会强引用。

  • block内部强引用的话为什么不直接引用?

在block里用strong引用保证持有应用的周期只在block被执行时,闭包函数返回后就被释放了。而直接引用,持有引用的周期则是block声明周期,就可能会造成循环引用。

相关文章

网友评论

    本文标题:使用Block何时需要WeakSelf和StrongSelf

    本文链接:https://www.haomeiwen.com/subject/xyohmttx.html