第一种定义方式(推荐)
以下内容摘自 YYKit
-
@weakify 宏定义
#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
-
@strongify 宏定义
#ifndef strongify #if DEBUG #if __has_feature(objc_arc) #define strongify(object) autoreleasepool{} __typeof__(object) object = weak##_##object; #else #define strongify(object) autoreleasepool{} __typeof__(object) object = block##_##object; #endif #else #if __has_feature(objc_arc) #define strongify(object) try{} @finally{} __typeof__(object) object = weak##_##object; #else #define strongify(object) try{} @finally{} __typeof__(object) object = block##_##object; #endif #endif #endif
-
使用举例
@weakify(self) [self doSomething^{ @strongify(self) if (!self) return; ... }];
注:block 外用 @weakify(self),block内用@strongify(self) ,不要问为什么,就是这么用的😄
第二种定义方式:
-
WeakSelf 宏定义:
#define WeakSelf(type) __weak typeof(type) weak##type = type
-
StrongSelf 宏定义
#define StrongSelf(type) __strong typeof(type) strong##type = type
-
使用举例
WeakSelf(self) [self doSomething^{ StrongSelf(self) if (!strongself) return; ... }];
注:使用起来相对麻烦,复制粘贴代码需要改动很多地方
网友评论