Suppose I have this code:
-(SomeOtherType*) getMyObject {
SomeType someObject = [[SomeType alloc] init];
// ... later on
SomeOtherType toReturn = [[[someObject interiorObject] retain] autorelease];
[someObject release];
return toReturn;
}
The toReturn object, am I handling it correctly? I want to deliver it as an autoreleased object, but I do want to scrap someObject. Is this the pattern to transfer ownership? I’ve gone over it in my head and on paper, and it seems OK, but I’d rather be informed by someone more enlightened.
Edit This is a very contrived example, just to illustrate the problem at hand. someObject lives across many method calls, and in the end, I want to “dump its guts”. This is NOT a Daily WTF example. Please don’t ridicule me. 🙂
The code you have provided in your question is correct. Lets go over why. When thinking about retain/release you need to think about ownership. Objects are typically owned by another object or within some particular scope. In this case
getByObject‘s scope. The object you want to return is theinteriorObjectwhich is owned bysomeObject. But you need to releasesomeObjectbefore you return. The proper thing to do is take ownership of theinteriorObjectand return an autoreleased copy. And finally release or autoreleasesomeObject.If ownership was not acquired to the
interiorObjectbefore the release ofsomeObjectthen theinteriorObjectcould be deallocated and we would be returning a dangling pointer. The first time someone tries to send a message to it the program would likely crash.