What are the reference counts of objects A and B after assigning B=A?

53 views Asked by At

What is the reference count of A and B after assigning B=A in this code?

Class1 *A=[[Class1 alloc] init];
Class1 *B=[[Class1 alloc] init];

[A retain];
NSMutableArray *tempArray= [NSMutableArray alloc]init];
[tempArray addobject:A];
B=A;
2

There are 2 answers

0
jscs On

This question seems to arise from a lack of distinction between the objects and the pointers to those objects. After your code has run, the objects pointed to by A and B have the same reference count value, because they are the same object. The assignment operation does not change the count of the object, and the pointers have no retain count. Only the objects do.

Objects are often talked about as if they are the same as their pointers -- "Pass object A into the method" -- because a) for the most part there's no relevant difference, and b) they can only be accessed via a pointer. This is one of the times that there's a relevant difference.

(After the assignment, the object that B originally pointed to has been leaked: it has a positive retain count but no pointers to it.)

2
Nils Ziehn On

Depends whether you use ARC, but since you have a retain in your code, I assume you don't use ARC.

Class1 *A=[[Class1 alloc] init];

A:1

Class1 *B=[[Class1 alloc] init];

A:1, B:1

[A retain];

A:2, B:1

NSMutableArray *tempArray= [NSMutableArray alloc]init];

A:2, B:1

[tempArray addobject:A];

A:3, B:1

UPDATE

B=A;

A:3, B:3 BUT the original B still exists with B':1