block 中 weakSelf/strongSelf 大法
2015-08-03 08:54
567 查看
在学习AFNetWorking的过程中,经常看到类似:
这是因为:没有添加__strong 引用的话,编译器会有警告,为什么会警告呢,因为弱引用的weakself会在某个时间被释放,有可能是在执行之后的block之前就会被释放,这样在后续的操作操作就有可能出错,所以最好是添加一个对weakSelf的__strong引用。
参考:
1 http://stackoverflow.com/questions/11899134/how-to-properly-address-weak-receiver-may-be-unpredictably-null-in-arc-mode
2 http://stackoverflow.com/questions/19018456/ios-blocks-and-strong-weak-references-to-self
原文点这里——–
[code]//__weak __typeof(self)weakSelf = self; //然后在block中,看到: //__strong __typeof(weakSelf)strongSelf = weakSelf; //如下边代码: - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler { [self.lock lock]; if (!self.backgroundTaskIdentifier) { UIApplication *application = [UIApplication sharedApplication]; __weak __typeof(self)weakSelf = self; self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ __strong __typeof(weakSelf)strongSelf = weakSelf; if (handler) { handler(); } if (strongSelf) { [strongSelf cancel]; [application endBackgroundTask:strongSelf.backgroundTaskIdentifier]; strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; } }]; } [self.lock unlock]; }
这是因为:没有添加__strong 引用的话,编译器会有警告,为什么会警告呢,因为弱引用的weakself会在某个时间被释放,有可能是在执行之后的block之前就会被释放,这样在后续的操作操作就有可能出错,所以最好是添加一个对weakSelf的__strong引用。
参考:
1 http://stackoverflow.com/questions/11899134/how-to-properly-address-weak-receiver-may-be-unpredictably-null-in-arc-mode
2 http://stackoverflow.com/questions/19018456/ios-blocks-and-strong-weak-references-to-self
原文点这里——–
相关文章推荐
- myeclipse报错: Errors occurred during the build. Errors running builder 'DeploymentBuilder' on project
- zoj 动态规划几题(简单)
- 使用frame, center ,bounds移动缩放对象
- objective-c内存解析
- unity 发布flash版本 调试需要flash player debug
- Test
- 关于使用sklearn进行数据预处理 —— 归一化/标准化/正则化
- poj 2356 Find a multiple(鸽巢原理+标记)
- 【转】java虚拟机参数详解之-Xms/-Xmx,运行时内存分配多少
- ./bin/spark-shell 报错:java.net.UnknownHostException
- Knockout应用开发指南
- Scikit Learn: 在python中机器学习
- Android 基础控件之进度条ProgressBar的实现
- JavaScript权威指南_146_第15章_脚本化文档_15.10-其他文档特性-Document的属性
- 取得viewController展示view
- 处理图片被渲染的效果
- UI 03 UITextField
- 权限管理(二)
- Knockout应用开发指南
- HDU 1864 最大报销额(01背包)