Search code examples
objective-ciphoneviewweak-referencesstrong-references

View's holding strong references?


Quick question: my ViewController has an IBOutlet for a UILabel would the ViewController's view automatically hold a strong reference to the label? And also, if I programmatically create a UIPopoverController ivar in ViewController and put the UIPopoverController ivar on the screen programmatically too would ViewController's view automatically hold a strong reference to that too?


Solution

  • You should keep a strong reference to any views that are not part of the view hierarchy. Your view controller already has a strong reference to its view property (the main view) and all subviews will be retained by their superview, so you don't actually need to hold a strong reference to them you can hold a weak reference to those views.

    However, if you have any view which is not in the main view (for example an additional view defined in the .xib file that you might add to your main view at some point later, or one of the child views that you want to remove and re-add programatically) then you should hold a strong reference to these views.

    Also note that when you hold a strong reference to a view in your view controller, you should set self.strongViewRef = nil in viewDidUnload because you don't need it when the view is unloaded (for example when the view controller is in the background eg. obscured by another full-screen view). The property will be automatically re-set to a new instance of that view when the view is loaded again.

    Regarding the popover, it will be retained while it is presented (by the window I think) but I would recommend holding a strong reference to it while you need it and then setting that pointer to nil once you are done with it. This way you guarantee that you can access it when you need to, which in some cases may be just before it is presented or just after it is dismissed.