15

Apple 文档说我可以通过捕获对自身的弱引用来避免强引用循环,如下所示:

- (void)configureBlock {
    XYZBlockKeeper * __weak weakSelf = self;
    self.block = ^{
        [weakSelf doSomething];   // capture the weak reference
                                  // to avoid the reference cycle
    }
}

然而,当我编写这段代码时,编译器告诉我:

由于竞态条件可能导致空值,因此不允许取消引用 __weak 指针,请先将其分配给强变量

然而,下面的代码不会创建一个强引用循环,并且可能会泄漏内存吗?

- (void)configureBlock {
    XYZBlockKeeper *strongSelf = self;
    self.block = ^{
        [strongSelf doSomething];
    }
}
4

1 回答 1

27

你应该像这样使用:例如:

__weak XYZBlockKeeper *weakSelf = self;

self.block = ^{

    XYZBlockKeeper *strongSelf = weakSelf;

    if (strongSelf) {
        [strongSelf doSomething];
    } else {
        // Bummer.  <self> dealloc before we could run this code.
    }
}
于 2013-07-24T03:21:20.377 回答