Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top