当 Objective-C 中启用 ARC 时,弱实例变量的内存管理如何在块内工作?

发布于 2024-12-29 08:35:45 字数 426 浏览 4 评论 0原文

当启用 ARC 时,在 Objective-C 中引用块内部的弱 ivar 时,运行时是否隐式保留 ivar 所属的对象?例如:

- (void) foo {
    void (^block)() = ^{
        [_weakIvar doSomethingAwesomeButNotTooAwesome]; // Is self retained here?
    }
    block();
}

当我们这样做时,在同一场景中弱属性怎么样?

- (void) foo {
    void (^block)() = ^{
        [self.weakProperty doSomethingAwesomeReallyAwesomeDudeYeah];
    }
    block();
}

When referencing a weak ivar inside of a block in Objective-C when ARC is enabled, does the runtime implicitly retain the object to which the ivar belongs? For example:

- (void) foo {
    void (^block)() = ^{
        [_weakIvar doSomethingAwesomeButNotTooAwesome]; // Is self retained here?
    }
    block();
}

While we're at it, how about a weak property in the same scenario?

- (void) foo {
    void (^block)() = ^{
        [self.weakProperty doSomethingAwesomeReallyAwesomeDudeYeah];
    }
    block();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

纵性 2025-01-05 08:35:45

_weakIvar 实际上意味着 self->_weakIvar 在底层,这意味着(自动)保留的是 self。同样的事情也适用于 self.weakProperty

在您的特定示例中,该块不会被复制(并立即使用),因此根本不会保留任何内容,但如果您这样做(例如):

- (void) foo {
    void (^block)() = ^{
        [_weakIvar doSomethingAwesomeButNotTooAwesome];
    }
    dispatch_async(queue, block); // here, block is copied and so self is retained
}

_weakIvar really means self->_weakIvar under the hood which means that what is (automatically) retained is self. Same thing applies when doing self.weakProperty.

In your particular example, the block is not copied (and used right away) so nothing is retained at all but if you do (for example):

- (void) foo {
    void (^block)() = ^{
        [_weakIvar doSomethingAwesomeButNotTooAwesome];
    }
    dispatch_async(queue, block); // here, block is copied and so self is retained
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文