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?
From what you have shown (which doesn't show how the class is implemented), here is a guess:
Test
class's copyWithZone:
method returns the receiver object itself, without retaining. (Which by the way is a violation of the memory management rules, which says that a method starting with copy
must return an owning (retained) instance. A class's copy
is allowed to return the object itself or a new object, but in both cases it must retain it.)t1
and t3
point to the same object, which only has 1 retain count, when the object was created. (Since the copy
incorrectly didn't retain.)t2
gets retained once, getting a retain count of 2, and the object pointed to by t1
and t3
gets retained twice, getting a retain count of 3.