iOS block中weakSelf和strongSelf的使用(分别什么时候用)
来源:互联网 发布:网址导航程序源码 编辑:程序博客网 时间:2024/05/18 19:21
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), ^{
[weakSelf doSomething];
[weakSelf 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 不会被释放。
总结
1 在 Block 内如果需要访问 self 的方法、变量,建议使用 weakSelf。
2 如果在 Block 内需要多次 访问 self,则需要使用 strongSelf。
- iOS block中weakSelf和strongSelf的使用(分别什么时候用)
- 【IOS学习】到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf
- IOS Block 的使用 weakSelf strongSelf
- OC的Block中使用weakSelf/strongSelf
- 到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf
- 到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf
- 到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf
- 到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf
- 到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf
- 到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf
- 到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf
- 到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf
- ObjC的Block中使用weakSelf/strongSelf @weakify/@strongify
- ObjC的Block中使用weakSelf/strongSelf @weakify/@strongify
- ObjC的Block中使用weakSelf/strongSelf @weakify/@strongify
- ObjC的Block中使用weakSelf/strongSelf @weakify/@strongify
- ObjC的Block中使用weakSelf/strongSelf @weakify/@strongify
- 在Block中使用weakSelf与strongSelf的意义
- 最大子数组与股票交易
- 0319 tabled 小练习
- java基础七(成员变量 局部变量 匿名对象 封装 设计原则 private this 构造方法 static)
- Path的moveTo、lineTo、quadTo、cubicTo、arcTo作用
- 借助百度云中的百度人脸识别用java开发一个人脸识别
- iOS block中weakSelf和strongSelf的使用(分别什么时候用)
- AI笔记 The SAT problem
- 前端获取时间的方式
- vue.js 部署到tomcat中出现访问路径不对,页面加载不出来问题及解决
- Yii2.0-redis扩展的搭建
- 不能访问本地服务器场。没有注册带有FeatureDependencyId 的 Cmdlet
- C++Builder 资料库 (转载)
- JAVA 极速WEB+ORM框架 JFinal
- 分布式架构学习一:dubbo管控台的安装