To __weak or not to __weak


#1

Hi, I am a bit confused with and issue with the instance’ variables, about to when to declare it __weak or not.

In the page 166 of the book, say:
"To avoid memory leaks, the convention for IBOutlets is to declare them as a weak references…"
That is because when you add the views with a .xib file, you have to references to it. One in the ViewController of the .xib file and other in the view property of the ViewController.

My question is, Why when you add your views programmatically we don’t have to declare them as __weak? I think that in this case we also have 2 strong references to each subview added to the view of ViewController, the one in the instance variable and the other added to the view.

Thanks in advance.


#2

So, if you were to declare an instance variable as weak, and then in loadView do this:

UIView *v = [[UIView alloc] init];
[self setView:v];

myWeakSubview = [UIButton buttonWithType:...];
[v addSubview:myWeakSubview];

The button would be destroyed before it was added to the view, because in between the assignment and addSubview:, the button does not have a strong reference.

The work-around here is:

UIButton *b = [UIButton buttonWithType:...];
[v addSubview:b];
myWeakSubview = b;

#3

Thank you Joe, it is clear for me now.