capturing self strongly in this block is likely to lead to a retain cycle,capturingretain
一個使用Block文法的執行個體變數,在引用另一個執行個體變數的時候,經常會引起retain cycle。
capturing self strongly in this block is likely to lead to a retain cycle
_items = [[NSMutableArray alloc] init]; _block = ^{ [_items addObject:@"Hello!"]; //_block引用了_items,導致retain cycle。 };
寫成下面格式
__block ViewController *blockSelf = self; _block = ^{ [blockSelf->_items addObject:@"Hello!"]; };
Capturing self strongly in this block is likely to lead to retain cycle
block 是代碼塊的意思。
甲裡引用乙,乙裡引用甲,就會導致 “retain cycle” -- “形成怪圈”的錯誤。
網上資料:
解決的辦法是 建立一個本地變數 指向 自己(self).
例如:_items 實際上是 self->items,
_block 對象在建立的時候會被retain一次
改成:
__block ViewController *blockSelf = self;
_block = ^{
[blockSelf->_items addObject:@"Hello!"];
};
就可以了。
-------------------
DoSomethingManager *manager = [[DoSomethingManager alloc] init];
manager.complete = ^{
//...complete actions
[manager otherAction];
manager.complete = nil; // Objective-C 用這種方法破壞怪圈。
[manager release];
};
-------------
報一個異常,問怎可以消除
解析出了問題,是木馬程式