objective-c - iOS开发,为避免循环引用有时我们会在block里使用weakSelf
本文介绍了objective-c - iOS开发,为避免循环引用有时我们会在block里使用weakSelf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
那么什么时候我们需要将weakSelf改为strong??
希望有经验的同学结合实例说明一下。?
提前感谢了。
解决方案
用__strong是为了保证对象在block执行前不被释放.
Demo: A 控制器(present)跳转到B, B dismiss回来.block里面有延时操作
.
使用没
__strong
时, 在B控制器dismiss
,secondVC
释放为nil, 1.0秒后block执行, 此时weakVC
为nil.使用
__strong
, 调用dismiss
, 由于block
有强引用,secondVC
不被释放(不是nil), 1.0秒后执行完block, 释放vc.
A控制器代码:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
SecondViewController *secondVC = [SecondViewController new];
__weak SecondViewController *weakVC = secondVC;
secondVC.secondBlock = ^(){
// // 在SecondViewController界面调用dismiss后,依然可以正常输出, VC dealloc
// __strong SecondViewController *strongVC = weakVC;
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// NSLog(@"%@",strongVC.view);
// });
// SecondViewController调用dismiss后被释放为nil, 打印为nil
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"%@",weakVC.view);
});
};
[self presentViewController:secondVC animated:YES completion:nil];
}
B控制器代码:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.secondBlock();
[self dismissViewControllerAnimated:YES completion:nil];
}
测试结果:
这篇关于objective-c - iOS开发,为避免循环引用有时我们会在block里使用weakSelf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文