iOS block中weakSelf和strongSelf的使用(分別什麼時候用)

Apple 官方的建議是,傳進 Block 之前,把 ‘self’ 轉換成 weak automatic 的變量,這樣在 Block 中就不會出現對 self 的強引用。如果在 Block 執行完成之前,self 被釋放了,weakSelf 也會變爲 nil。

示例代碼:

__weak __typeof__(self) weakSelf = self;    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

[weakSelf doSomething];

});

clang 的文檔表示,在 doSomething 內,weakSelf 不會被釋放。但,下面的情況除外:

__weak __typeof__(self) weakSelf = self;  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

[weakSelf doSomething];

[weakSelf doOtherThing];

});

在 doSomething 中,weakSelf 不會變成 nil,不過在 doSomething 執行完成,調用第二個方法 doOtherThing 的時候,weakSelf 有可能被釋放,於是,strongSelf 就派上用場了:

__weak __typeof__(self) weakSelf = self;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

__strong __typeof(self) strongSelf = weakSelf;

[strongSelf doSomething];

[strongSelf doOtherThing];

});

__strong 確保在 Block 內,strongSelf 不會被釋放。

總結

1 在 Block 內如果需要訪問 self 的方法、變量,建議使用 weakSelf。

2 如果在 Block 內需要多次 訪問 self,則需要使用 strongSelf。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章