Objective-C 内存管理(分配和自动释放)

发布于 2024-08-19 07:07:08 字数 257 浏览 3 评论 0原文

当您分配并初始化对象,然后想要返回该对象时,您应该如何返回它?

我有以下代码:

NSXMLDocument* fmdoc = [[NSXMLDocument alloc] initWithContentsOfURL:trackInfoUrl
    options:NSXMLDocumentTidyXML error:&err];  
return [fmdoc autorelease];

这是正确的吗?

When you allocate and initialize and object, and then want to return that object, how are you supposed to return it?

I have the following code:

NSXMLDocument* fmdoc = [[NSXMLDocument alloc] initWithContentsOfURL:trackInfoUrl
    options:NSXMLDocumentTidyXML error:&err];  
return [fmdoc autorelease];

Is this correct?

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

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

发布评论

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

评论(1

苍暮颜 2024-08-26 07:07:08

这是正确的。由于您正在初始化该对象,因此您有责任释放或自动释放它。

由于创建时的保留计数为 1,并且您希望在调用方法有机会使用该对象之前不删除它,因此 autorelease 是要发送的正确消息。

如果你发送了release,内存就会立即被回收。通过发送 autorelease,内存将不会被回收,直到默认的自动释放池耗尽为止,直到调用方法有机会保留对象(如果需要)之后才会发生这种情况。

That is correct. Since you are initializing the object, it is your responsibility to release or autorelease it.

As the retain count on creation is 1 and you want it to not be deleted before the calling method has a chance to use the object, autorelease is the correct message to send.

If you had sent it release, the memory would have been reclaimed immediately. By sending it autorelease the memory will not be reclaimed until the default autorelease pool is drained, which won't happen until after the calling method has had a chance to retain the object if it needs to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文