使用塊保留`self`循環 - Retain cycle on `self` with blocks

問題:

I'm afraid this question is pretty basic, but I think it's relevant to a lot of Objective-C programmers who are getting into blocks. 我擔心這個問題非常基本,但我認爲這與很多進入數據塊的Objective-C程序員有關。

What I've heard is that since blocks capture local variables referenced within them as const copies, using self within a block can result in a retain cycle, should that block be copied. 我聽到的是,因爲塊捕獲它們作爲const副本引用的局部變量,所以在塊中使用self可以導致保留週期,如果該塊被複制。 So, we are supposed to use __block to force the block to deal directly with self instead of having it copied. 所以,我們應該使用__block來強制塊直接處理self而不是複製它。

__block typeof(self) bself = self;
[someObject messageWithBlock:^{ [bself doSomething]; }];

instead of just 而不僅僅是

[someObject messageWithBlock:^{ [self doSomething]; }];

What I'd like to know is the following: if this is true, is there a way that I can avoid the ugliness (aside from using GC)? 我想知道的是:如果這是真的,有沒有辦法可以避免醜陋(除了使用GC)?


解決方案:

參考一: https://en.stackoom.com/question/IGIb
參考二: https://stackoom.com/question/IGIb
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章