Search code examples
iphoneiosmemory-managementrelease-managementretain

NSMutableArray and memory managment


I am learning Objective C coming from a language which has garbage collection and I am struggling with memory management. In particular I am struggling with what happens in this instance.

// Global variable
NSMutableArray *parentArray;

// Instance
- (void)testing {
  parentArray = [[NSMutableArray alloc] init]; 
  NSMutableArray *childArray = [[NSMutableArray alloc] init];

  [childArray addObject:@"mike"];
  [parentArray addObject:childArray];
}

childArray is a pointer to an array so when I addObject it to the parentArray does it copy it or pass the pointer? If, like I think, it passes the pointer I can't [childArray release] in this method as it would destroy the object and I wouldn't be able to read from it elsewhere.

Therefore do I have to release it in the main dealloc method at the end of the class?

Any help greatly appreicated as I'm struggling.

Mike


Solution

  • NSMutableArray (and all other standard objective-c containers) retain objects added to them, so you can release your childArray right after it was added to parentArray.

    Moreover immediate release will improve your code readability - as it is clear that object ownership passes to the parentArray.