首页 > 开发 > iOS > 正文

iOS开发,为避免循环引用有时我们会在block里使用weakSelf

2017-09-08 13:45:14  来源:网友分享

那么什么时候我们需要将weakSelf改为strong??
希望有经验的同学结合实例说明一下。?
提前感谢了。

解决方案

用__strong是为了保证对象在block执行前不被释放.
Demo: A 控制器(present)跳转到B, B dismiss回来.block里面有延时操作.

  1. 使用没__strong时, 在B控制器dismiss, secondVC释放为nil, 1.0秒后block执行, 此时weakVC为nil.

  2. 使用__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];}

测试结果: