block循环引用

一.使用__weak

1)ARC环境下:ARC环境下可以通过使用_weak声明一个代替self的新变量代替原先的self,我们可以命名为weakSelf。通过这种方式告诉block,不要在block内部对self进行强制strong引用

2)MRC环境下:解决方式与上述基本一致,只不过将__weak关键字换成__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宏(推荐)

/**

* 强弱引用转换,用于解决代码块(block)与强引用self之间的循环引用问题

* 调用方式: `@weakify_self`实现弱引用转换,`@strongify_self`实现强引用转换

*

* 示例:

* @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

/**

* 强弱引用转换,用于解决代码块(block)与强引用对象之间的循环引用问题

* 调用方式: `@weakify(object)`实现弱引用转换,`@strongify(object)`实现强引用转换

*

* 示例:

* @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

参考:MRC/ARC通用的weakify和strongify - yoyoso的个人页面 - 开源中国社区

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容