iPhone Memory Management - Part 1

In review of a project today, I realize I need to write down some general rules on memory management around Objective-C.

I'm going to write more on this but here are some general rules:

Case 1. Setting properties.

Obj *obj = [[obj alloc] init];
myClient.obj = obj;
[obj release];


This assumes the property is either retain or copy. Either way, it's the receiver's responsibility to make sure the memory is being retained.

Case 2: Returning obj

- (Obj) foo{
Obj *obj = [[[Obj alloc] init] autorelease];
return obj;
}


When sending an obj as return, always set it to auto release. This is basically the same principle as "Clean up after yourself".

Case 3: Array Manipulation

Sometimes you need to create a Mutable Array, populate it and return an Array. What I recommend is the following:

- (NSArray) foo{
NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
... Build the array.. read from the database and populate it, etc.
NSArray *rtnArray = [NSArray ArraywithArray:tmpArray]; //This is an autorelease copy.
[tmpArray release];
return rtnArray;

That's the basic cases I have in mind right now. I will continue to write as I come across them this weekend.