使用ARC和块时保留周期

Avn*_*arr 2 objective-c ios objective-c-blocks automatic-ref-counting retain-cycle

根据我的理解,当一个对象方法接收一个块作为完成参数时,我可以在块中发送"self":

[object doMethodWithCompletion:^{
  [self doSomethingWhenThisMethodCompletes]
}];
Run Code Online (Sandbox Code Playgroud)

但是如果这个对象"保留"该块(保存它以备将来使用),我应该发送一个"弱"的自己的副本:

__weak __typeof__(self) weakSelf = self;
object.savedBlock = ^{
  [weakSelf doSomethingWhenThisBlockIsCalledFromWithinObject];
};
Run Code Online (Sandbox Code Playgroud)

但我也见过变种,如:

__weak __typeof__(self) weakSelf = self;
object.savedBlock = ^{
  __typeof__(weakSelf) strongSelf = weakSelf;
  [strongSelf doSomethingWhenThisBlockIsCalledFromWithinObject];
};
Run Code Online (Sandbox Code Playgroud)

我不清楚为什么/何时做最后一个变种

Seb*_*ian 5

在块内创建一个强引用可确保在块运行时,对象不会在块的中途解除分配,这可能会导致意外的,难以调试的行为.

typeof(self) weakSelf = self;
[anObject retainThisBlock:^{
    [weakSelf foo];
    // another thread could release the object pointed to by weakSelf
    [weakSelf bar];
}];
Run Code Online (Sandbox Code Playgroud)

现在[weakSelf foo]会跑,但[weakSelf bar]不会,因为现在是weakSelf nil.如果在块内创建强引用,则在块返回之前无法释放对象.