views:

349

answers:

1

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?

+2  A: 

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.

mbarnett
Correct, but I would discourage any mention of specific retain counts as, on creation, the retain count might be any number depending on internal implementation details. Much more constructive to think of retain counts as something you add to and subtract from, but never query the value directly.
bbum
@bbum fair enough
mbarnett
@bbum, amazing comment, that changes my way of thinking.
Yar