开发者

how reference copy is handled in Objective-C?

Object graph

      [Instance A]
         tree
       /       \
      /         \
     /           \
    ↓             ↓
[Instance B]     [Instance C]
 apple            开发者_运维百科  bug

Question

Instance A has to reference copies to Instance B and Instance C.

If I retain or release Instance A, which has references to the other two instances, what happens to the various reference counts?


When you retain or release A, only its reference count changes. What happens to B and C depends on your model and implementation.

If A "owns" or needs to keep B/C around, it should retain it at some point (independent of A itself being retained), and release it when A is being deallocated.

If you're not implementing A, you need to check the documentations to see whether it owns B/C or you need to explicitly retain and release them.

I checked your original question, not sure if this is the answer you're looking for. If not, explain it a bit...


You do not care about retain counts. No, honestly you don't. You only care about whether A owns B and C (or more accurately, has a share in the ownership of B and C).

So presumably somewhere you have a method that sets the children of A (it might be A's designated initialiser). If that method retains B and C then A must release B and/or C when it no longer needs ownership. This will be in two circumstances:

  1. when B and/or C are to be overwritten with new children
  2. When A is about to be deallocated

Anyway, having said that, to answer your question:

If you retain A it has no effect on the retain counts of B and C.

If you release A it has no effect on the retain count of B and C unless nobody else has ownership of A. In this case A's dealloc will be invoked which will release both B and C.


When you call the retain or release on objectA nothing will happen with the objects which hold the the reference of objectA. (Unless you have overridden these methods.)(retain increases retain count and release decreases retain count)

Incase of release, if the retain count becomes 0, dealloc will get called and objectA is released. And you are responsible for releasing the allocated objects of the class. The other objects which still hold the reference of objectA become dangling pointers.

Regards, Dhana.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜