Reputation: 22515
Which one of these is better practice?
A) retain and release the object myself later
NSMutableArray* array = [[self getArray] retain];
....
[array release];
B) autorelease from the function returning the object
getArray {
NSMutableArray* returnedArray = [[[NSMutableArray alloc] init] autorelease];
.....
return returnedArray;
}
Upvotes: 0
Views: 852
Reputation: 63667
new
, alloc init
, retain
, or copy
(NARC) an object, you have to release it.release
the object when he is done with it.retain
on the object.Some comments:
Example:
// created with autoreleased, just call retain if you intend to keep it
NSString *orange = [NSString stringWithString:@"orange"];
// created for the caller, you'll have to release it when you are done
NSObject *apple = [NSString initWithString:@"apple"];
Upvotes: 0
Reputation: 14148
You could read and follow Apples guidelines on memory management and performance.
Personally I think the reasons for choosing one way over the other:
Using Autorelease pros:
cons:
Using retain/release pros:
cons:
I think, whichever style you choose comes down to the situation your code is in and choosing the best style based on there pro's and con's. I don't think there is any one answer to this.
Upvotes: 2
Reputation: 13686
The simplest rule of thumb when it comes to memory management in Objective-C is that you should release anything that you've explicitly allocated (alloc), copied (copy), newed up (new), or retained (retain).
The release should be done within the scope of the aforementioned actions. If you allocate space for an object that is returned by a method, you should autorelease it before returning it. So, given the two options you've provided, B is the recommended practice.
Upvotes: 4
Reputation: 14063
If you want to return an object you have to use the second approach. In all cases where possible you should use the retain-release approach because this uses less memory.
Upvotes: 2