Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weak IBOutlet UIView property would become nil

I have two UIViews in the nib file and I set them to be properties of my view controller, using the IBOutlet and weak keyword.

However, when I use self.view1 which I want to use to point to the view in the nib, for the first time, it works. But when I use it later, these two properties turn to be nil.

Using the strong property would fix the issue. But I always use weak for the IBOutlet property. Why it becomes nil in this situation?

like image 892
Gon Avatar asked Mar 26 '14 04:03

Gon


1 Answers

You need to have a strong reference to top level items in a nib file. If you have two views at the top level of your nib, then you should have strong references to them, not weak ones.

Any subviews of these top level views can be made IBOutlets with weak references, because the top level view keeps a strong reference to these subviews, so you don't have to.

Most times, weak is good enough, because there is an implicit strong reference to the top level object. For Example, if you have a nib for a view controller, then the view controller object maintains a strong reference to the top level view because of it's view property, which means that you can have a weak hold on any other objects.

like image 55
Abizern Avatar answered Oct 07 '22 10:10

Abizern