当 Objective-C 中启用 ARC 时,弱实例变量的内存管理如何在块内工作?
当启用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
_weakIvar
实际上意味着self->_weakIvar
在底层,这意味着(自动)保留的是self
。同样的事情也适用于self.weakProperty
。在您的特定示例中,该块不会被复制(并立即使用),因此根本不会保留任何内容,但如果您这样做(例如):
_weakIvar
really meansself->_weakIvar
under the hood which means that what is (automatically) retained isself
. Same thing applies when doingself.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):