Release object after return?
Say I have an object initialized right before a method's return statement...
MyObj* myObj = [[MyObj alloc] initWithOpt1:opt1 withOpt2:opt2];
return myObj;
Is it possible 开发者_Go百科to release
it after the return statement? Doing so before defeats the purpose of init'ing it to begin with, right? Otherwise, what's the best way to handle this?
Autorelease was created precisely to solve this problem.
MyObj* myObj = [[MyObj alloc] initWithOpt1:opt1 withOpt2:opt2];
return [myObj autorelease];
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html
Just do
return [myObj autorelease];
that's it!
While
return [myObj autorelease];
works it is better coding educate to simply
return myObj;
and then when you create the object do it with an autorelease on it.
MyObj *my_obj = [[[MyObj alloc] initWithOpt1:opt1 withOpt2:op2] autorelease];
and the reason for this is because autorelease is saying that when this function is over I want to release this object. So using
return [myObj autorelease];
is not the only way.
精彩评论