//聯系人:石虎QQ: 1224614774昵稱:嗡嘛呢叭咪哄
一、避免循環引用
如果【block內部】使用【外部聲明的強引用】訪問【對象A】,那么【block內部】會自動產生一個【強引用】指向【對象A】
如果【block內部】使用【外部聲明的弱引用】訪問【對象A】,那么【block內部】會自動產生一個【弱引用】指向【對象A】
__weak typeof(self)weakSelf = self;
dispatch_block_t block = ^{
[weakSelf doSomething];// weakSelf != nil
// preemption,weakSelf turned nil
[weakSelf doSomethingElse];// weakSelf == nil
};
二、最好這樣調用:
__weak typeof(self)weakSelf = self;
myObj.myBlock = ^{
__strong typeof(self)strongSelf = weakSelf;
if(strongSelf){
[strongSelf doSomething];// strongSelf != nil
// preemption,strongSelf still not nil(搶占的時候,strongSelf還是非nil的)
[strongSelf doSomethingElse];// strongSelf != nil }
else { // Probably nothing... return;
}
};