开发者

Objective-C memory management (alloc and autorelease)

When you allocate and initialize and ob开发者_如何学Cject, 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜