[英]Do I need to check for nil on my strongSelf = weakSelf assignment inside a block?
例如,我正在使用SVInfiniteScrolling( https://github.com/alexanderedge/SVInfiniteScrolling )。
我有一些看起來像這樣的代碼...
- (void)initializeInfiniteScrollingForTableView {
__weak MyViewController *weakSelf = self;
[self.tableView addInfiniteScrollingWithActionHandler:^{
MyViewController *strongSelf = weakSelf;
if (!strongSelf.endReached) {
[strongSelf fetchData];
}
else {
[strongSelf.tableView.infiniteScrollingView stopAnimating];
}
}];
}
我想知道的是...在像這樣使用之前,我是否需要檢查strongSelf是否為零...
...
[self.tableView addInfiniteScrollingWithActionHandler:^{
MyViewController *strongSelf = weakSelf;
if (strongSelf) { // <== ** Is this needed? **
if (!strongSelf.endReached) {
這就是為什么我問。 從此鏈接上的第3點( http://www.apeth.com/iOSBook/ch12.html#EXstrongWeakDance )來看, “零測試是因為在多線程情況下,我們對自我的弱引用可能已從在我們之前沒有進行下一步;那么它將為零,因為它是ARC的弱參考,在那種情況下將毫無意義。
需要這張支票嗎? 我以為您是第一次在塊中使用對weakSelf的引用時,該表達式會在表達式持續時間內保留嗎?
我認為在您看來:
if (!strongSelf.endReached) {
如果self為零,則結果將為YES,這可能不是您想要的。
碰巧您的代碼做了正確的事情(什么也不做),因為兩個子句都只使用self來調用方法,然后什么也不會發生。 最終結果與進行nil-check相同,但是執行路徑錯誤。 如果有人添加了不使用self的代碼,將來可能會產生后果。
對於您發布的代碼,無需檢查nil
。
這行代碼:
if (!strongSelf.endReached) {
如果strongSelf為nil,則將評估為false。 進一步閱讀: 向nil發送消息?
然后這行代碼將執行:
[strongSelf.tableView.infiniteScrollingView stopAnimating];
如果strongSelf為零,那么該行將根本不執行任何操作(甚至不會出錯)。
但是,一些開發人員認為最好還是檢查nil,以防萬一有人后來添加了代碼並且確實關心nil。 因此,您應該考慮這樣做:
MyViewController *strongSelf = weakSelf;
if (!strongSelf) {
return;
}
... the rest of your code ...
您的消息來源是指這樣的事實,即weakSelf
在執行該塊之前, weakSelf
可能已被釋放並nil
; 因此,在strongSelf
獲得強大的參考並保留之前。 所述strongSelf
是確保通過引用的對象weakSelf
不是nil
塊的執行期間 “d。
ARC中沒有“使用”變量的概念,因此在處理__weak
變量時有必要retain
它__weak
__weak
明確選擇退出。
話雖這么說,在這種情況下檢查並不是嚴格意義上的,因為發送到nil
消息始終是無操作的。 如果您打算將strongSelf
插入一個數組中,或者如果在消息之間取消分配它會使您的程序處於無效狀態,那將是另一回事。
總而言之,每當需要確保__weak
變量在一段時間內不會nil
時,請使用__strong
,並在使用前檢查它是否為nil
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.