第一種定義方式(推薦)
以下內(nèi)容摘自 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內(nèi)用@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; ... }];
注:使用起來相對麻煩,復(fù)制粘貼代碼需要改動很多地方