Objective-C 内存管理(分配和自动释放)
当您分配并初始化对象,然后想要返回该对象时,您应该如何返回它?
我有以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是正确的。由于您正在初始化该对象,因此您有责任释放或自动释放它。
由于创建时的保留计数为 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.