Santosh Gurram
Santosh Gurram

Reputation: 1017

Effect on object before and after retain & copy

I have two questions:

  1. I have an object, call it X. When I assign retain to object X ([x retain]) and then change data in the object X, what will be the retain count of X?

  2. I have two objects, A & B. I first do a copy like this:

    B = [A copy];

and now I change data in object A. Will the B data also change, and what will be reference count of both A & B before and after the change of data?

Upvotes: 0

Views: 144

Answers (2)

jscs
jscs

Reputation: 64002

  1. The same as it was before you changed the data.

  2. i. No, you have two independent objects after you copy. Changing one no longer affects the other.
    ii. The same as they were before you changed the data.

Please have a look at Apple's Memory Management essay.

Upvotes: 1

morningstar
morningstar

Reputation: 9132

For 1, if you mean change the data like x.foo = y, the retain count doesn't change. If you mean x = y, then the retain count of x changes to whatever the retain count of y is, because x is y.

For 2,

The data of B is unchanged. The retain count of B is 1. The retain count of A is the same as before the copy.

That's the normal case, but I think an object can choose to return a non-new object from copy. I think non-mutable NSStrings will return themselves as the copy, so the retain count of B might not be 1, and the retain count of A will be increased by 1. Basically, you can't rely on it.

Upvotes: 0

Related Questions