問題:
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