Apple docs说我可以通过捕获对自我的弱引用来避免强引用周期,如下所示:
- (void)configureBlock {
XYZBlockKeeper * __weak weakSelf = self;
self.block = ^{
[weakSelf doSomething]; // capture the weak reference
// to avoid the reference cycle
}
}
然而,当我编写这段代码时,编译器会告诉我:
由于可能为null,因此不允许取消引用__weak指针 由竞争条件引起的价值,首先将其分配给强变量
然而,以下代码是否会创建一个强引用循环,并可能泄漏内存?
- (void)configureBlock {
XYZBlockKeeper *strongSelf = self;
self.block = ^{
[strongSelf doSomething];
}
}
答案 0 :(得分:18)
你应该像这样使用: 例如:
__weak XYZBlockKeeper *weakSelf = self;
self.block = ^{
XYZBlockKeeper *strongSelf = weakSelf;
if (strongSelf) {
[strongSelf doSomething];
} else {
// Bummer. <self> dealloc before we could run this code.
}
}