objective-carraysmemory-managementretainretaincount

Memory management in objective c arrays


For this question:

Test *t1 = [[Test alloc]init];
Test *t2 = [Test new];
Test *t3 = [t1 copy];

NSLog(@"Retain count of Object 1 : %ld",[t1 retainCount]);
NSLog(@"Retain count of Object 2 : %ld",[t2 retainCount]);
NSLog(@"Retain count of Object 3 : %ld",[t3 retainCount]);

NSArray *arr = @[t1,t2,t3];

NSLog(@"Retain count of Object 1 : %ld",[t1 retainCount]);
NSLog(@"Retain count of Object 2 : %ld",[t2 retainCount]);
NSLog(@"Retain count of Object 3 : %ld",[t3 retainCount]);

The answer is:

Retain count of Object 1 : 1
Retain count of Object 2 : 1
Retain count of Object 3 : 1
Retain count of Object 1 : 3
Retain count of Object 2 : 2
Retain count of Object 3 : 3

I can understand that adding an object to an array increases its reference count by 1, but for objects 1 & 3 it increases by 2?? Can someone answer this?


Solution

  • From what you have shown (which doesn't show how the class is implemented), here is a guess: