Search code examples
iosmemory-managementcopyretaincount

Retain count while copying


I am quiet new with memory management. I know my question has already been discussed on StackOverflow. But I would like to know the answer to understand it completely. My question is:

NSMutableArray *firstArray = [[NSMutableArray alloc]init];
NSMutableArray *secondArray = [[NSMutableArray alloc] init];
secondArray = [firstArray copy];

what will be retain count for firstArray and the secondArray after copy?


Solution

  • 1 for each. firstArray is holding the pointer to firstArray. When you call secondArray = [firstArray copy];, the contents of firstArray are copied to a new memory location and secondArray will point to that location. This means that firstArray and secondArray will be pointing to separate memory locations (and are different objects), although they have the same data. Therefore, they each have a retain count of 1.