美文网首页
weakSelf strongSelf

weakSelf strongSelf

作者: 心愿2016 | 来源:发表于2016-08-07 14:34 被阅读51次

解决 retain circle

Apple 官方的建议是,传进 Block 之前,把 ‘self’ 转换成 weak automatic 的变量,这样在 Block 中就不会出现对 self 的强引用。如果在 Block 执行完成之前,self 被释放了,weakSelf 也会变为 nil。

示例代码:

__weak __typeof__(self) weakSelf = self;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

[weakSelf doSomething];

});

clang 的文档表示,在 doSomething 内,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 执行完成,调用第二个方法 doOtherThing 的时候,weakSelf 有可能被释放,于是,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 内如果需要访问 self 的方法、变量,建议使用 weakSelf。

如果在 Block 内需要多次 访问 self,则需要使用 strongSelf。

相关文章

  • RN 调 js 核心代码

    ^{RCTJSCExecutor *strongSelf = weakSelf;if (!strongSelf |...

  • 宏定义

    1.weakSelf和strongSelf

  • 不一样的书写样式

    **********************1.block中weakSelf 与 strongSelf******...

  • StrongSelf

    weakSelf : 防止循环引用 strongSelf: 防止释放 需要 强引用weakSelf,主要是处理一...

  • weakSelf/strongSelf

    1.Retain Circle的由来 当A对象里面强引用了B对象,B对象又强引用了A对象,这样两者的retainC...

  • weakSelf & strongSelf

    循环引用 循环引用不做过多的解释,两个对象互相持有对方,谁都无法先被释放掉。循环引用经常是由于使用block而引起...

  • weakSelf strongSelf

    解决 retain circle Apple 官方的建议是,传进 Block 之前,把 ‘self’ 转换成 we...

  • iOS宏定义

    1 weakself和strongself #ifndef weakify #if DEBUG #ifhas_fe...

  • weakSelf 或 strongSelf

    在block中为了防止循环引用会使用weakSelf 或者 strongSelf那么什么时候使用weakSelf,...

  • ObjC的Block中使用weakSelf/strongSelf

    学习block帖子ObjC的Block中使用weakSelf/strongSelf @weakify/@stron...

网友评论

      本文标题:weakSelf strongSelf

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