那么什么时候我们需要将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];}
测试结果: