ios - 使用 ARC 和 block 时保留循环

标签 ios objective-c automatic-ref-counting objective-c-blocks retain-cycle

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

[object doMethodWithCompletion:^{
  [self doSomethingWhenThisMethodCompletes]
}];

但是如果这个对象“保留”该 block (保存它以供将来使用)我应该发送我自己的“弱”副本:

__weak __typeof__(self) weakSelf = self;
object.savedBlock = ^{
  [weakSelf doSomethingWhenThisBlockIsCalledFromWithinObject];
};

但我也看到过一些变体,例如:

__weak __typeof__(self) weakSelf = self;
object.savedBlock = ^{
  __typeof__(weakSelf) strongSelf = weakSelf;
  [strongSelf doSomethingWhenThisBlockIsCalledFromWithinObject];
};

我不清楚为什么/何时进行最后一个变体

最佳答案

在 block 内创建强引用可确保如果 block 运行,对象不会在 block 中途被释放,这可能会导致意外的、难以调试的行为。

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

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

关于ios - 使用 ARC 和 block 时保留循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20325708/

相关文章:

ios - 如果出现键盘,则自动对齐表示

ios - Swift:字符后的字符串firstIndex

iphone - 如何让 xcode 自动选择正确的平台 lib(.a)

ios - 如何在标签中写多行

ios - YouTube WebUIViewDelegate - respondsToSelector : being sent to the wrong instance

objective-c - 在 XCode 4.3.2 中,当我运行 ARC 转换重构工具时,我所有的 "retain"属性选项都没有更改为 "strong"

ios - 关于 ARC 功能

ios - 有了 MainViewController,如何在 MainVC 中与实际的 UIContainerViews 通信?

ios - 如何调试 ARC 在不应该删除对象时删除对象

iphone - 从外部路径加载 TTF 字体