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