一.使用__weak
1)ARC環(huán)境下:ARC環(huán)境下可以通過使用_weak聲明一個代替self的新變量代替原先的self肠阱,我們可以命名為weakSelf贴铜。通過這種方式告訴block涯塔,不要在block內(nèi)部對self進行強制strong引用
2)MRC環(huán)境下:解決方式與上述基本一致找爱,只不過將__weak關(guān)鍵字換成__block即可
例子:
__weak __typeof(self) weakSelf = self;
[self executeBlock:^(NSData *data, NSError *error) {
? ?[weakSelf doSomethingWithData:data];
}];
多個語句的例子:
__weak __typeof(self)weakSelf = self;
[self executeBlock:^(NSData *data, NSError *error) {
__strong __typeof(weakSelf) strongSelf = weakSelf;
if (strongSelf) {
? [strongSelf doSomethingWithData:data];
? [strongSelf doSomethingWithData:data];
}
}];
二.使用weakify和strongify宏(推薦)
/**
* 強弱引用轉(zhuǎn)換作煌,用于解決代碼塊(block)與強引用self之間的循環(huán)引用問題
* 調(diào)用方式: `@weakify_self`實現(xiàn)弱引用轉(zhuǎn)換掘殴,`@strongify_self`實現(xiàn)強引用轉(zhuǎn)換
*
* 示例:
* @weakify_self
* [obj block:^{
* @strongify_self
* self.property = something;
* }];
*/
#ifndef? ? weakify_self
#if __has_feature(objc_arc)
#define weakify_self autoreleasepool{} __weak __typeof__(self) weakSelf = self;
#else
#define weakify_self autoreleasepool{} __block __typeof__(self) blockSelf = self;
#endif
#endif
#ifndef? ? strongify_self
#if __has_feature(objc_arc)
#define strongify_self try{} @finally{} __typeof__(weakSelf) self = weakSelf;
#else
#define strongify_self try{} @finally{} __typeof__(blockSelf) self = blockSelf;
#endif
#endif
/**
* 強弱引用轉(zhuǎn)換,用于解決代碼塊(block)與強引用對象之間的循環(huán)引用問題
* 調(diào)用方式: `@weakify(object)`實現(xiàn)弱引用轉(zhuǎn)換粟誓,`@strongify(object)`實現(xiàn)強引用轉(zhuǎn)換
*
* 示例:
* @weakify(object)
* [obj block:^{
* @strongify(object)
* strong_object = something;
* }];
*/
#ifndef? ? weakify
#if __has_feature(objc_arc)
#define weakify(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;
#endif
#endif
#ifndef? ? strongify
#if __has_feature(objc_arc)
#define strongify(object) try{} @finally{} __typeof__(object) strong##_##object = weak##_##object;
#else
#define strongify(object) try{} @finally{} __typeof__(object) strong##_##object = block##_##object;
#endif
#endif