ios - 非平凡循环中的 block

标签 ios objective-c memory-management automatic-ref-counting objective-c-blocks

我阅读了以下 article但我对以下段落有点困惑。

Apple documentation says that “For non-trivial cycles, however, you should use” this approach:

MyViewController *myController = [[MyViewController alloc] init…];
// ...
MyViewController * __weak weakMyController = myController;
myController.completionHandler =  ^(NSInteger result) {
    MyViewController *strongMyController = weakMyController;
    if (strongMyController) {
        // ...
        [strongMyController dismissViewControllerAnimated:YES completion:nil];
        // ...
    }
    else {
        // Probably nothing...
    }
};

First of all, this example looks wrong to me. How can self be deallocated and be nilled out if the block itself is retained in the completionHandler property? The completionHandler property can be declared as assign or unsafe_unretained to allow the object to be deallocated after the block is passed around. I can’t see the reason for doing that. If other objects need the object (self), the block that is passed around should retain the object and therefore the block should not be assigned to a property. No _weak/_strong usage should be involved in this case.

  1. 他说“如果其他对象需要对象(self):” 他这里的需要是什么意思?是这样的吗:他们需要 self ,因为他们访问需要 self 的 block (传递给他们的 block ),所以他们需要 self 。如果不是他是什么意思?

  2. 然后他说“因此不应将 block 分配给属性。” 但是,如果有多个对象需要在未来某个未定义的时间阻塞怎么办?因此,我们可以通过从该属性中获取来将 block 传递给他们。

我是不是理解错了?

最佳答案

这篇文章的作者有点糊涂,把一些东西弄反了。

How can self be deallocated and be nilled out if the block itself is retained in the completionHandler property?

如果 block 保留在 completionHandler 中,则意味着 self 对该 block 具有强引用,这意味着只要 self 是——而不是相反。 self 保留 block 与 self 是否被释放无关。

The completionHandler property can be declared as assign or unsafe_unretained to allow the object to be deallocated after the block is passed around.

同样,completionHandler 是强引用还是弱引用会影响 block 的生命周期。它与self的生​​命周期指向的对象无关。

If other objects need the object (self), the block that is passed around should retain the object and therefore the block should not be assigned to a property.

没有。该对象保留该 block 。该 block 不保留对象。

在大多数情况下是否需要代码示例中显示的模式是值得商榷的。然而,作者的推理是错误的。

关于ios - 非平凡循环中的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20619183/

相关文章:

objective-c - 添加到数组后保留计数会增加吗?

c++ - 删除元素后,(c++) vector 会缩小吗?

java - 如何最大限度地减少应用程序使用的内存?

ios - 当城市名称等于某个国家的名称时,CLGeocoder 返回错误的结果(不仅如此)

ios - 卡在 Xcode 中的文件名

iphone - 如何定位正确的图片路径

c - 为什么在 c 中实现链表时使用动态内存分配(即 malloc())?

ios - 如何快速克隆对象模型

ios - 使用CoreText将丰富的UITextView中的文本对齐段落?

objective-c - 当 xcode 中的设备方向发生变化时,我将如何加载 xib?