Search code examples
iosobjective-cweak-references

Weak references and Retain cycles


I'm developing an application that using ARC,so I have 3 cases:

1 @property (strong, nonatomic) IBOutlet UILabel *titleLabel;

That means: titleLable has a strong references to superView and superView has a strong references to titleLabel?

2 @property (weak, nonatomic) IBOutlet UILabel *titleLabel;

That means: titleLable has a weak references to superView and superView has a strong references to titleLabel?

3 I declare:

UILabel *titleLabel = [[UILabel alloc] initWithFrame:self.view.bounds];
[self.view addSubview:titleLabel]

Could everyone answer my questions?

  • My description for case 1 and 2 are correct?

  • In case 1, can the superView release or not? because i think titleLable has a strong reference to supperView

    • In case 3, why we dont need declare __weak for titleLabel, maybe superView can be release in this case? Thanks for your responses.

Solution

  • The other answers here are good, but I want to be extra clear about a misconception you seem to have. Properties on classes are one-way relationships, not two.

    So you ask in each case about how that property references its owner (strong or weak) but the reality is that it doesn't reference it at all. In fact no object has any knowledge of what other objects own it at any given time. The only thing that it tracks is how many objects own it. If you want a two way relationship where both objects have a reference to each other, that is when you need a weak reference in at least one direction. Otherwise, both object are making sure the other never gets dealloced and therefore neither will ever be dealloced. That is what is called a "circular reference". It can happen between more than two objects as well where A has a strong reference to B, B has a strong reference to C, and C has a strong reference to A.

    Now, regarding the "superview" method on UIViews. This will always be a weak reference and is setup automatically when you add a subview. This is because the parent view always has a strong reference to all of its children. If a child ever had a strong reference to its parent, there would be a circular reference. But please note, that adding a property to a view, does not automatically add it as a subview, that must still be done manually in code or inside a xib or storyboard.

    So in short, only case 3 creates reference between the view and the label because you added it as a subview. Then self.view has a strong reference to the label. As a completely different mechanism, the view then adds a weak reference to itself on the subview called "superview".