標籤:
源地址:http://fann.im/blog/2013/04/17/retain-cycle-in-blocks/
個人筆記,可能會有理解不夠透徹而錯誤。 @fannheyward
Objective-C 是基於引用計數(retainCount)來做記憶體管理,ClassA 用到 ClassB 的時候,通過 alloc/retain/copy 等將 objectB.retainCount+1,不需要的時候通過 release/autorelease 將 objectB.retainCount-1. retainCount 歸零後對象 objectB 被釋放。假如 objectA retain objectB,objectB 反過來也 retain objectA,結果就是兩者 retainCount 都無法歸零,也就沒辦法被釋放,造成記憶體泄露。這就是 Retain Cycle。
一般情況下注意避免兩個對象互相 retain 就不太會出現 Retain Cycle,但是在用到 Blocks 的時候就要小心,很容易造成 Retain Cycle。這是因為 Blocks 會自動 retain 它引用的對象(block 裡的對象),稍不留神就造成 Retain Cycle。文檔: Object and Block Variables:
When a block is copied, it creates strong references to object variables used within the block. If you use a block within the implementation of a method:
- If you access an instance variable by reference, a strong reference is made to self;
- If you access an instance variable by value, a strong reference is made to the variable.
To override this behavior for a particular object variable, you can mark it with the __block storage type modifier.
MRC
一個簡單的例子,Xcode 會報 Retain Cycle warning:
UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect];[imgView setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // ... imgView.image = image; // warning: Capturing ‘imgView‘ strongly in this block is likely to lead to a retain cycle}];
block 也是一個對象,[imgView setImageWithURL:completed:] 的時候 retain 了這個 block;而 block 又自動的 retain 了 imgView,所以就造成了 Retain Cycle。解決方案就是用 __block 告訴 block 不要 retain 引用的對象:
__block UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect];[imgView setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // ... imgView.image = image;}];
還有一種情況,block 裡引用的對象是 self 或者 self.property,解決方案同理:
__block MyClass *myClass = self;operation.completeBlock = ^(NSInteger index) { [myClass doOther];};self.imgView = [[UIImageView alloc] initWithFrame:rect];__block UIImageView *tmpView = _imgView;[_imgView setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { tmpView.image = image;}];}
ARC
在 ARC 下不能用 __block 關鍵字,取而代之的是 __weak 或者 __unsafe_unretained。其中 __weak 只能 iOS 5+ 使用,__unsafe_unretained 支援 iOS 4。如果 App 不需要考慮 4.x 用 __weak 會更好一些,__weak 修飾的對象釋放後會被設定為 nil,而 __unsafe_unretained 會繼續指向原來的記憶體。
__block MyClass *myClass = self; // MRC__weak MyClass *myClass = self; // ARC & iOS 5+__unsafe_unretained MyClass *myClass = self; // ARC & iOS 4.
一些參考文章:
- iOS blocks - 三個會造成retain cycle的anti patterns
- Friday Q&A 2010-04-30: Dealing with Retain Cycles
- ASIHTTPRequest Using blocks
- ARC - The meaning of __unsafe_unretained?
- IOS中的block和retain cycle
iOS 8:【轉】Block循環參考