Earl Grey
Earl Grey

Reputation: 7466

ViewDidLoad and ARC and XIBs

Given that we are writing code with ARC, should I nil properties in viewDidUnload, that are instantiated from:

  1. XIB (here the nilling is sometimes generated from IDE)

  2. from initialiser and have not IBOutlet

  3. that are weak

?

Upvotes: 1

Views: 311

Answers (2)

Rob
Rob

Reputation: 437432

The purpose of viewDidUnload is to give your app a chance to remove references to user interface objects that may no longer exist because the view was removed upon receiving a memory warning. Thus:

  1. You should be setting any user interface controls to nil (because the view is being unloaded). Unnecessary for weak properties (and they generally should be weak per Apple guidance on this topic), but if Xcode inserts it in for you, it's not a problem. For guidance on what to do in viewDidUnload see the "Memory Warnings" section of the Resource Programming Guide: The Nib Files.

  2. And for non-user interface objects that you set up in viewDidLoad, I'd be wary about just blindly setting those to nil in viewDidUnload, especially if you're not using ARC (e.g. if you accidentally nil the instance variable, you might cause a leak). And you probably want to balance the amount of memory that will be recovered versus the "cost" of re-retrieving that data (e.g. if it's from some remote server). Regardless, I'd suggest that you handle the freeing of memory for non-UI objects in didReceiveMemoryWarning.

In my mind, I view viewDidUnload as a chance to make sure I'm not maintaining references to user interface objects that might no longer exist, and I use didReceiveMemoryWarning to empty caches or other non-UI related items that I can safely purge to recover some memory. And if you're concerned about iOS 6, note that the handling of viewDidUnload may be changing, and while the NDA precludes us from discussing it publicly, I might advise that you may want to refer to the iOS 6 Beta 4 Release Notes and look for references to viewDidUnload.

Upvotes: 1

Mazyod
Mazyod

Reputation: 22559

Your general rules:

  1. nil all strong IBOutlets only. Leave weak ones alone.
  2. nil all properties instantiated in viewDidLoad, and not init, initWithCoder: and initWithNibName:bundle:.

You should also nil properties that are recreated "on-the-fly" or have a nil check, to free up more memory.

Upvotes: 1

Related Questions