今天做一個初始化資料後重新整理某個界面資料功能,
在代碼塊使用__weak typeof(self) weakSelf = self 放在代碼塊外部,内部使用[weakSelf test] 方法 調用 ;
但是,由于這部分代碼塊使用計時器循環調用,是以當我前面幾個方法執行完了之後 [weakSelf test] 方法 weakself 會 為 nil
網上查了一下
這是因為:沒有添加__strong 引用的話,編譯器會有警告,為什麼會警告呢,因為弱引用的weakself會在某個時間被釋放,有可能是在執行之後的block之前就會被釋放,這樣在後續的操作操作就有可能出錯,是以最好是添加一個對weakSelf的__strong引用。
在學習AFNetWorking的過程中,經常看到類似:
__weak __typeof(self)weakSelf = self;
然後在block中,看到:
__strong __typeof(weakSelf)strongSelf = weakSelf;
如下代碼:
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
[self.lock lock];
if (!self.backgroundTaskIdentifier) {
UIApplication *application = [UIApplication sharedApplication];
__weak __typeof(self)weakSelf = self;
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (handler) {
handler();
}
if (strongSelf) {
[strongSelf cancel];
[application endBackgroundTask:strongSelf.backgroundTaskIdentifier];
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
}];
}
[self.lock unlock];
}
參考文章:AFNetWorking 學習