Under the Bridge

View Controller memory

Here’s a tip to take to heart for your didReceiveMemoryWarning implementations in your view controllers: stash the superview before calling [super didReceiveMemoryWarning] so you don’t immediately recreate it.

[EDIT: Apparently our commenters are more clued in than both us and the original tipster. Your view controllers will get didReceiveMemoryWarning even if their view hasn't been loaded yet ... which means that if you follow this tip, the first thing you'll do is load the view. That is not a sensible response to low memory conditions. Therefore, you should check that your views have indeed been loaded!]

So, a really defensive implementation would look like this:

 

- (BOOL)viewIsLoaded
{
   return nil != _sharedPlayer; // or whatever viewDidLoad setup you can test
}

- (void)didReceiveMemoryWarning
{
   if (![self viewIsLoaded])
      return;

    UIView* superview = self.view.superview;

    // Releases the view if it doesn't have a superview
    [super didReceiveMemoryWarning];

    if ( superview == nil )
    {
        // OK. NOW we can assume view is gone.
    }

     // Destroy any caches regardless here
}

This is for the good of people who have their own memory issues, of course, not people who have imageNamed kill the system behind their back. Which isn’t us, yet. But some day it might be!

h/t: iPhoneKicks!

2
  • http://www.benzado.com/ Benjamin Ragheb

    Doesn’t the system notify *every* view controller on a memory warning? If so, then the view might already be loaded, and your code will force it to load just at the moment when memory is tightest.

    This is *worse* than reloading the view after the superclass implementation release is, because at least in that case you aren’t increasing the total memory footprint of the app.

  • http://www.alexcurylo.com/ Alex

    Yikes! Yes, you’re quite right, you will indeed get -didReceiveMemoryWarning even if the view never loaded. That possibility had completely escaped me, along with the author of this tip. Good catch. I’ll sort that out.