-2

"A common use case for the weak attribute is parent-child data structures. By convention, the parent object should maintain a strong reference with it’s children, and the children should store a weak reference back to the parent. Weak references are also an inherent part of the delegate design pattern."

Question:

1) Why the children can store a weak reference back to the parent? What if their parents "disappear"?

2) What does the delegate design pattern here refers to? What does it have to do with weak references?

Chenya Zhang
  • 463
  • 3
  • 11
  • 22
  • Many duplicates like http://stackoverflow.com/questions/8449040/why-use-weak-pointer-for-delegation and http://stackoverflow.com/questions/14249395/reference-a-views-parent-without-getting-a-circular-import – Ozgur Vatansever Sep 21 '16 at 03:01
  • @ozgur I don't think you understand my question well? I'm asking why it "can" not "should". I know the retain cycle behind. – Chenya Zhang Sep 21 '16 at 03:06
  • 1
    I guess the "can" is related to what you want to happen to the child when the parent is deallocated. As long as you are happy for the children to also be deallocated (in the absence of any other strong reference to the child) then you can use a weak reference. Same with a delegate. It is often simpler to use a weak reference to the delegate, so that the delegate object doesn't have to explicitly remove itself as an object's delegate in order to allow itself to be deallocated. – Paulw11 Sep 21 '16 at 03:10

1 Answers1

1

For question 1, if the parent is released, the weak reference in a child will become a reference to a deallocated object, and using it will cause an exception.

The way to avoid this circumstance is to make it the responsibility of the parent to release it's children upon it's deallocation. The child will never have a weak reference to a deallocated parent because that child would have been deallocated when the parent was.

For question 2, here's a good reference for the delegate pattern.

danh
  • 62,181
  • 10
  • 95
  • 136