简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM