在Block中使用weakSelf与strongSelf的意义
我们都会声明一个弱引用在block
中使用, 目的就是防止循环引用, 那么weakSelf
与strongSelf
一起使用目的是什么呢? 首先先定义2个宏:
#define YXWeakSelf(type) __weak typeof(type) weak##type = type; #define StrongSelf(type) __strong typeof(type) type = weak##type;
在Controller中YXWeakSelf(self)
与YXStrongSelf(self)
一起使用情况很多,为了防止循环引用,还是不懂原因的见如下实例:
我们创建一个shop
并且在shop.myBlock
代码块中使用弱引用YXWeakSelf(shop)
LRShop *shop = [[LRShop alloc]init];shop.string = @"welcome to our company";//弱引用YXWeakSelf(shop)shop.myBlock = ^{NSLog(@"%@",weakshop.string);};shop.myBlock();
YXWeakSelf(shop)
与YXStrongSelf(shop)
一起使用
LRShop *shop = [[LRShop alloc]init];shop.string = @"welcome to our company";//弱引用YXWeakSelf(shop);shop.myBlock = ^{//强引用YXStrongSelf(shop)NSLog(@"%@",shop.string);};shop.myBlock();
这2个打印结果都是shop.string
有值并且shop
也销毁了, 看起来是没什么区别:
仅仅使用YXWeakSelf(shop)
并且在myBlock
中增加一个延迟3秒在输出就会出现问题, 虽然对象销毁了, 输出的值却是null
//弱引用YXWeakSelf(shop);shop.myBlock = ^{dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{NSLog(@"%@",weakshop.string);});};shop.myBlock();
如果YXWeakSelf(shop)
与YXStrongSelf(shop)
一起使用输出的shop.string
有值,对象也销毁了, 我就不再截图给大家看了!
//弱引用YXWeakSelf(shop)shop.myBlock = ^{//强引用YXStrongSelf(shop)dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{NSLog(@"%@",shop.string);});};shop.myBlock();
通过上面一堆的解释, 我们明显发现YXWeakSelf(shop)
与YXStrongSelf(shop)
一起使用的好处, 不但能打印出我想要的值,而且也不会造成循环引用 , 在开发中这两个方法可以根据实际情况进行使用!