Reputation: 43401
In most of the code that I've sen using autorelease, the object is ultimately returned from the function.Clearly release cannot be called after this point and autorelease is the way to go. However in situations where the object is going to passed to another object that will retain it is using autorelease just as valid?
For example
-(void)foo
{
SomeClass *someObject = [[[SomeClass alloc] init] autorelease];
//Do some things
self.someOtherClass.someProperty = someObject;
}
Is there any practical difference to releasing the object after it is assigned to someProperty:
-(void)foo
{
SomeClass *someObject = [[SomeClass alloc] init]];
//Do some things
self.someOtherClass.someProperty = someObject;
[someObject release];
}
Are there any situations where the later is more preferable to the former?
Upvotes: 1
Views: 104
Reputation: 9162
I think the latter will always perform slightly better in terms of memory usage and CPU usage, but only by a tiny amount per allocation.
Feel free to use the former if you prefer not to write three lines of code and are not having a performance problem. Note that the former can actually be written in one statement without a local variable at all.
Upvotes: 0
Reputation: 14672
Both are acceptable, but you are accouraged to use the release version to avoid memory spikes an other problems.
It's acceptable to release here because you can assume that the receiver of the object will retain it, if it needs if later. So you can safely release as soon as it's given.
Upvotes: 1