用__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 *)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 *)touches withEvent:(UIEvent *)event
{
self.secondBlock();
[self dismissViewControllerAnimated:YES completion:nil];
}
测试结果: