如果【block內(nèi)部】使用【外部聲明的強引用】訪問【對象A】, 那么【block內(nèi)部】會自動產(chǎn)生一個【強引用】指向【對象A】。
如果【block內(nèi)部】使用【外部聲明的弱引用】訪問【對象A】, 那么【block內(nèi)部】會自動產(chǎn)生一個【弱引用】指向【對象A】
__weak typeof(self) weakSelf = self;
dispatch_block_t block = ^{
[weakSelf doSomething]; // weakSelf != nil
// preemption, weakSelf turned nil
[weakSelf doSomethingElse]; // weakSelf == nil
};
最好這樣調(diào)用:
__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;
}
};