block引用的改写

如果【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;

}

};

你可能感兴趣的:(block引用的改写)