First of all you have to understand, that objectA
and objectB
are not (Objective-C) objects. They are references to objects. (Objects have retain counts, not references to objects.)
So, your situation is correctly:
objectA
points to an object that has a RC of 1.
objectB
points to an object that has a RC of 0.
The second sentence is a paradox: There is never an object with RC 0, because reaching a RC 0 would deallocate the object. So there is no object anymore. (In practice a RC of 0 is never reached, because the object is deallocated when the RC is going to be 0. But this is an implementation detail and therefore not important.)
The statement …
objectB = [objectA retain];
… increases the RC of the object*, objectA
points to. The return value of -retain
is the value of the receiver pointer (objectA
). This reference is then assigned to objectB
. Therefore objectB
– still being a reference – points to the same object, objectA
points to. Since RCs are owned by the object, there is only one object and only one RC. It is 2.
Remark* Even it is documented that -retain
increments the RC, this is not always that way. There are objects with eternal liefe time, having a virtual marker RC. However, I will keep the answer simple, so we assume that every execution of -retain
increments the RC. But try this:
id ref = @"RC";
NSLog(@"%lu", [ref retainCount]);
[ref retain];
NSLog(@"%lu", [ref retainCount]);
You get:
2017-04-01 22:09:21.214 reftest[74967:8550738] 18446744073709551615
2017-04-01 22:09:21.215 reftest[74967:8550738] 18446744073709551615
Something increased? No.
But for the same reason you should never think in absolute values of RC ("a RC of 1"), but in changing a value at a location in source code: After a retain the RC is usually greater by 1 than it has been before. After a release the RC is usually less than 1 it has been before. Calculating a absolute value you have to consider all strong references to that object, what is impossible. And it is meaningless, because it is the strength of RC, that you think reference by reference instead of all references together.