代码
#define WeakSelf @weakify(self);
#define StrongSelf @strongify(self);
#ifndef weakify
#if DEBUG
#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
#else
#if __has_feature(objc_arc)
#define weakify(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;
#endif
#endif
#endif
#ifndef strongify
#if DEBUG
#if __has_feature(objc_arc)
#define strongify(object) autoreleasepool{} __typeof__(object) strong##_##object = weak##_##object;
#else
#define strongify(object) autoreleasepool{} __typeof__(object) block##_##object = block##_##object;
#endif
#else
#if __has_feature(objc_arc)
#define strongify(object) try{} @finally{} __typeof__(object) strong##_##object = weak##_##object;
#else
#define strongify(object) try{} @finally{} __typeof__(object) block##_##object = block##_##object;
#endif
#endif
#endif
分析
一,不能设置宏为全局变量:
将宏设置为全局变量时,使用WeakSelf 或者使用weakify(self) 是没有问题的. 但是弱引用的对象不是self, 而是一个webView ,那么就可能会释放不掉. 所以将上面的宏作为一个局部变量.
二,typeof(object) 和__typeof(object)的区别.
两种写法都可以,但是建议宏使用__typeof__(object)
结语
博客旧版原文在CSDN上:https://blog.csdn.net/luochuanAD/article/details/78845104