2

Trying to understand the strong vs weak reference in Objectice-C by reading this explanation, it makes prefect sense to me. But there is one scenario that I cannot really figure it out.

Suppose it's in ARC environment, and I will use -(hyphen) as strong reference and .(dot) as weak reference for now. Let's say I have a View Controller object MyViewController vc = [MyViewController alloc] init]; and it has view, so their relation is like

vc ------ view

with strong reference. Once vc is deallocated, view will also be deallocated.

If I want to add subviews to the view, for example, UILabel, from Interface Builder and connect it to the object, usually I will have declare a weak reference ivar @property (weak, nonatomic) IBOutlet UILabel *myLabel because the view already have a strong reference to it. So now the relationship looks like

vc ------ view ------ myLabel

and

vc .................. myLabel

So when vc is deallocated, view gets deallocated, and then myLabel also gets deallocated. But what if I also set a strong reference between vc and mylabel, the relationships between now become

vc ------ view ------ myLabel

and

vc ------ myLabel

When vc is deallocated, will myLabel also get deallocated? I think so because no objects have strong reference to it now. But I want to make sure. Please let me know if I am missing anything here. Thanks in advance.

Community
  • 1
  • 1
Dino Tw
  • 3,167
  • 4
  • 34
  • 48

1 Answers1

1

First of all - good explanation to your question, well done.

Short answer to your question - when vc is deallocated, myLabel will also be deallocated even if it holds a strong reference to it.

Because or how the strong/retain relationship works. Here's some pseudocode

vc --- view --- myLabel

vc.dealloc {
  [myLabel release]; // reduces retainCount by 1, doesn't dealloc
  [view release]; // reduces retainCount by 1, triggers dealloc
}

view.dealloc {
  [myLabel release]; // triggers dealloc
}
Eugene
  • 10,006
  • 4
  • 37
  • 55
  • Thank you for the pseudocode, my understanding is the same. From this [discussion](http://stackoverflow.com/a/7729141/691626) which has a link to Apple's document, the subview(the myLable in my example) should have weak reference. It seems that Apple still recommends weak reference for subviews even though there will be no logic error with strong reference in implementation. – Dino Tw Apr 19 '14 at 14:57