一般iOS程序员都在写block时,如果block与self构成了闭环,通常都会使用套装
在block外:__weak typeof(Class*) weakSelf = self;
在block里:__strong typeof(Class*)strongSelf = weakSelf;
大家都是搬砖的,有说的不对的地方指正就好,我说说我的理解:
很多人都觉得__strong typeof(Class*)strongSelf = weakSelf;的写法其实是多余的,都是邯郸学步,却不知所以,其实__strong typeof(Class*)strongSelf = weakSelf;有他专属的用法。
先上代码实践一下,在.h先定义
typedef void (^ClassBlock)(NSString*str);
@interface WeakClassVC : UIViewController
@property(nonatomic,copy)ClassBlock blk;
-(void)gogogo:(ClassBlock)bl;
@end
.m实现
- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:@selector(implementBlock) withObject:nil afterDelay:5];
// Do any additional setup after loading the view.
__weak typeof(WeakClassVC*)weakSelf = self;
self.blk = ^(NSString * _Nonnull str) {
//NSLog(@"%s-%@-%@",__func__,str,self);//引起循环引用
NSLog(@"%s-%@-%@",__func__,str,weakSelf);//打断闭环
//模拟延迟操作 主要为了模拟weak是否安全
//页面销毁了 block里的线程还继续操作
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (int i = 0; i<10000; i++) {
NSLog(@"GCD----%@",weakSelf);
}
});
};
}
-(void)implementBlock{
if (self.blk) {
self.blk (@"block执行");
}
}
看看测试结果:问题就出现了,dealloc后,weak已经为空
2021-07-01 10:07:57.162068+0800 WeakTest[42003:2288511] GCD----<WeakClassVC: 0x7f8ac1f11000>
2021-07-01 10:07:57.175028+0800 WeakTest[42003:2288511] GCD----(null)
2021-07-01 10:07:57.175038+0800 WeakTest[42003:2287346] -[WeakClassVC dealloc]
2021-07-01 10:07:57.175166+0800 WeakTest[42003:2288511] GCD----(null)
2021-07-01 10:07:57.175259+0800 WeakTest[42003:2288511] GCD----(null)
2021-07-01 10:07:57.175349+0800 WeakTest[42003:2288511] GCD----(null)
我们再来看看使用__strong typeof(Class*)strongSelf = weakSelf;
__strong typeof(weakSelf)strongSelf = weakSelf;
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (int i = 0; i<10000; i++) {
NSLog(@"GCD----%@--%@",weakSelf,strongSelf);
}
});
同样再次在进入线程耗时操作瞬间退出页面,看看结果如何:
2021-07-01 10:10:25.929987+0800 WeakTest[42131:2291602] GCD----<WeakClassVC: 0x7fed29e05880>--<WeakClassVC: 0x7fed29e05880>
2021-07-01 10:10:25.930144+0800 WeakTest[42131:2291602] GCD----<WeakClassVC: 0x7fed29e05880>--<WeakClassVC: 0x7fed29e05880>
2021-07-01 10:10:25.930371+0800 WeakTest[42131:2291602] GCD----<WeakClassVC: 0x7fed29e05880>--<WeakClassVC: 0x7fed29e05880>
2021-07-01 10:10:25.930503+0800 WeakTest[42131:2291375] -[WeakClassVC dealloc]
结果很明显,至少在这种场景下,/加入strong 不会出现页面销毁了 block里还会继续执行未完成的事情。
搬砖道路千万条,适合自己场景的最安全!!
不对回复,留下你的宝贵见解就好!!