Retain, alloc, properties ... Topic to make your Obj-c life easier !
17:58 22 Mar 2010

The more I code, the more I get lost ... so I decided to create a topic entirely dedicated to the memory management for me (and others) not to waste hours understanding obj-c basics ... I'll update it as new questions are asked !

Okay below is some examples :

// myArray is property (retain)
myArray = otherArray;

//myArray isn't a property
myArray = otherArray;

//myArray is a property (retain)
myArray = [[NSArray alloc] init];

//myArray isn't a property
myArray = [[NSArray alloc] init];

--- So, if I understand ... when you put self.myArray you tell Xcode to use the getter or setter but when you just do myArray, you are responsible for everything, right ?

[SOLVED] UPDATE1 : Is there a difference between :

//myArray is a property
myArray = otherArray; // it is only a reference, releasing otherArray will imply releasing myArray
self.myArray = otherArray; // otherArray is sent a retain message so releasing otherArray will still keep myArray in memory

--- Yes, there is a difference (see comments above)

[SOLVED] UPDATE2 : Is myArray below equal to nil ?

NSArray *myArray;

--- Kubi : Yes, it is equal to nil.

[SOLVED] UPDATE3 : does it count for 2 retains ? One retain from self and one retain from alloc ? Is this a memory leak ?

self.myArray = [[NSArray alloc] init];

--- Kubi : Yes, this is a memory leak !

[SOLVED] UPDATE4 : the property takes care of everything ? no need to alloc or release ?

self.myArray = [NSArray array];

--- We here use the setter so that the array is retained properly

[SOLVED] UPDATE5 : Are these two blocks the same ?

//myArray is a retained property

self.myArray = [NSArray array]; //retain
self.myArray = nil; //release and set to nil

myArray = [[NSArray alloc] initWithArray]; //retain
self.myArray = nil; //release and set to nil

--- Kubi : Yes, they're identical

Thanks for the time.

Gotye.

objective-c iphone nsarray allocation retain