2014-07-17 20 views
-1

有一堆關於所有這些薄弱和強大的自我的問題,但我想,你們在我的特殊例子接過來一看:弱和強烈的自我使用,塊存儲管理

- (void)getItemsWithCompletionHandler:(void (^)(NSArray*items))completionHandler { 
__weak __typeof__(self) weakSelf = self; 
[self doWorkWithCompletionHandler:^(Response *response) { 
    // this completion is not on main thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     ... 
     [weakSelf doAnotherWorkWithCompletionHandler:^(Response *response) { 
      // this completions is not on main thread either 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       __typeof__(self) strongSelf = weakSelf; 
       NSArray *itemsIds = [strongSelf doWorkOnMainThread1]; 
       NSArray *items = [strongSelf doWorkOnMainThread2]; 
       completionHandler(items); 
      }); 
     }]; 
    }); 
}]; 
} 

是一切正確的位置或不?也歡迎您提出重構建議

+3

這個問題可能會更好地排序在[Codereview](http://codereview.stackexchange.com/) –

+0

在外部局部範圍內聲明'itemsIds'和'items'有什麼意義?這不是那個範圍在異步操作中分配給這兩個變量時會存在。 – newacct

+1

是什麼讓你覺得你需要弱引用? – newacct

回答

0

您應該檢查completionHandler是否爲NULL,然後調用它。

if (completionHandler) { 
    completionHandler(items); 
} 

否則你會崩潰,如果completionHandler爲NULL


,如果你想打電話completionHandler(items)在所有如果self == nil在任何時候,你也可以考慮一下。我這麼說,因爲有一點不一致。
在行

[weakSelf doAnotherWorkWithCompletionHandler:^(Response *response) { 

如果weakSelf是已經爲零,那麼它的completionHandler不會被調用,並在結果completionHandler(items)也不會被調用。

但在這裏:

__typeof__(self) strongSelf = weakSelf; 
NSArray *itemsIds = [strongSelf doWorkOnMainThread1]; 
NSArray *items = [strongSelf doWorkOnMainThread2]; 
completionHandler(items); 

如果self == nil然後completionHandler實際上將被調用。

當然,我沒有看到整個圖片,也許它是完全不相關的,但你可能想要考慮的事情。

進一步說,我想你寧願completionHandler稱爲在每一個場景,即使self == nil在任何點。或者在出現任何問題時向其添加錯誤參數。


如果你想成爲超級迂腐,你可能想要把__weak類型之後,因爲這樣的:

__typeof__(self) __weak weakSelf = self; 

這是首選的方法:https://developer.apple.com/library/ios/releasenotes/objectivec/rn-transitioningtoarc/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226-CH1-SW4(尋找「你應該裝點變量正確的。「)

1

如果你把所有的警告,那麼你會得到一個警告的

[weakSelf doAnotherWorkWithCompletionHandler... ]; 

您不應該將消息發送給弱對象。當被調用的方法正在運行時,弱對象可能會消失。將弱對象存儲爲強對象,結果不是零。如果你再調用

[strongSelf doAnotherWorkWithCompletionHandler... ]; 

你知道,無論是strongSelf ==零,沒有任何反應,或者strongSelf是,雖然該方法執行不保持爲零。