弱引用與強引用
__weak typeof(type) 與 __strong typeof(type)稳吮。
typeof()可以根據(jù)括號里面的變量端朵,自動識別變量類型并返回該類型宣决。__weak弱引用淑玫,__strong強引用
- 使用的方式
- 默認使用方式
__weak __typeof__(self) weakSelf = self; __strong __typeof__(weakSelf) strongSelf = weakSelf;
- 宏定義使用
1. 使用@WeakSelf的方式,這種方式用法有點像原生使用(個人感覺略微裝逼的使用方式捆毫,但是用著不爽闪湾,代碼不主動補全(可以拉成代碼塊,然后就好了)) #define WeakSelf(type) autoreleasepool{} __weak __typeof__(type) weakSelf = type; #define StrongSelf(type) autoreleasepool{} __strong __typeof__(type) strongSelf = type; // 如此定義之后可以在這句代碼之后直接使用變量weakSelf @WeakSelf(self); weakSelf.title = @"下一個界面"; // 例如如此使用 // 強引用也是如此 @StrongSelf(weakSelf); // 這里是weakSelf strongSelf.title = @"下一個界面"; 2. 使用WeakSelf #define WeakSelf(type) __weak __typeof__(type) weakSelf = type; #define StrongSelf(type) __strong __typeof__(type) strongSelf = type; // 如此定義之后可以在這句代碼之后直接使用變量weakSelf WeakSelf(self); weakSelf.title = @"下一個界面"; // 例如如此使用 // 強引用也是如此 StrongSelf(weakSelf); // **這里是weakSelf** strongSelf.title = @"下一個界面";
- 另一個宏定義的方式
#define selfWeak(type) autoreleasepool{} __weak typeof(type) type##Weak = type; #define selfStrong(type) autoreleasepool{} __strong typeof(type##Weak) type##Strong = type##Weak; 或者 #define selfWeak(type) __weak typeof(type) type##Weak = type; #define selfStrong(type) __strong typeof(type##Weak) type##Strong = type##Weak; 這是對第一種的擴展绩卤,可以適應(yīng)更多的方式途样。我使用selfWeak,只是想保持第二個變量大寫濒憋。 當然你也可以使用這種方式 #define WeakSelf(type) __weak typeof(type) weak##type = type; #define StrongSelf(type) __strong typeof(weak##type) strong##type = weak##type; // 如此定義之后可以在這句代碼之后直接使用變量weakself WeakSelf(self); weakself.title = @"下一個界面"; // 例如如此使用 // 強引用也是如此 StrongSelf(self); // **這里是self** strongself.title = @"下一個界面";
- 區(qū)別一就是第一個只適用與self何暇,另一個使用面廣。
- 區(qū)別二用法上凛驮,第一個StrongSelf(weakSelf)裆站,另一個StrongSelf(self)。就是第二個會自動處理變量名字。