MRC/ARC通用的weakify和strongify

来源:互联网 发布:网上考勤软件 编辑:程序博客网 时间:2024/06/11 21:59

http://my.oschina.net/ioslighter/blog/393555?p=1

准备将项目中的代码逐步转换为ARC,存在MRC与ARC并存的情况,想用一个通用的办法来解决循环引用的问题,找到了这份代码,太好了,一劳永逸。使用方法见注释: 

本文链接:http://my.oschina.net/ioslighter/blog/393555

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 强弱引用转换,用于解决代码块(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

来源:

https://github.com/PFei-He/PFTabView/blob/master/PFTabView/PFTabView.h


0 0