2013-07-24 11 views
2

Apple docs說,我可以通過捕獲的弱引用自我,這樣可以避免強烈的參考週期:解引用__weak的指針是不允許的內部塊

- (void)configureBlock { 
    XYZBlockKeeper * __weak weakSelf = self; 
    self.block = ^{ 
     [weakSelf doSomething]; // capture the weak reference 
            // to avoid the reference cycle 
    } 
} 

然而,當我寫這篇文章的代碼,編譯器告訴我:

解引用一個指針__weak不允許由於由爭用條件可能爲空值 ,其分配到強可變第一

但下面的代碼不會創建一個強大的引用循環,並可能泄漏內存?

- (void)configureBlock { 
    XYZBlockKeeper *strongSelf = self; 
    self.block = ^{ 
     [strongSelf doSomething]; 
    } 
} 
+0

嘗試'__weak XYZBlockKeeper * weakSelf'代替。看到'*'右側的'__weak',我感到不舒服(這可能沒有什麼區別,但試試看,如果確實如此,那麼我有一個理論爲什麼)。 – borrrden

+2

就像一個旁註,我無法得到這個消息出來。這是說你正在做'weakSelf-> memberVariable = 123;' – borrrden

+0

@borrden這樣的警告如果你設置了'-Wreceiver-is-weak'標誌(可以用「發送消息到__weak指針」構建設置)。另外,將'__weak'放在星號後面會更明智,因爲'__weak'適用於'weakSelf'(因爲weakSelf將被設置爲零,而weakSelf不會被設置爲零)。考慮'typedef XYZBlockKeeper * XYZBlockKeeperRef; XYZBlockKeeperRef __weak weakSelf;'聲明弱引用,但'typedef __weak XYZBlockKeeper WeakXYZBlockKeeper; WeakXYZBlockKeeper * weakSelf;'不(並且得到'__weak'不適用的警告)。 –

回答

11

你應該使用這樣一個: 如:

__weak XYZBlockKeeper *weakSelf = self; 

self.block = ^{ 

    XYZBlockKeeper *strongSelf = weakSelf; 

    if (strongSelf) { 
     [strongSelf doSomething]; 
    } else { 
     // Bummer. <self> dealloc before we could run this code. 
    } 
} 
+3

在這個特殊的例子中,你不需要檢查'strongSelf'。你可以發送消息給'無';什麼都沒發生。 –

+3

但有什麼區別(除了警告消失)? – newacct