陈斌彬的技术博客

Stay foolish,stay hungry

MRC/ARC通用的weakify和strongify

今天在阅读 Monkey 项目源代码中,看到这个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