views:

3709

answers:

3

When does UIViewController's viewDidUnload automatically get called? Yes I know, when the view unloads. But when does that happen automatically? How can I do it manually? Thanks.

+2  A: 

If you issue a memory warning in the simulator (look in the menu), this will get called for any view controller attached to a view that is not visible.

That's because view controllers by default are registered for memory warning notifications, and any view that is not currently being used will be unloaded by the view controller - the viewDidUnload method is there so that you can clean up anything else you would like, to save extra memory (or if you've retained some IBOutlets to help free up memory that would otherwise be released by the view being unloaded).

Generally any IBOutlets you release in dealloc, should also be released (and references set to nil) in this method.

Kendall Helmstetter Gelner
It won't get called for my app then because I only ever have one view controller instantiated at a time, when I switch them first I deallocate (self.vc = nil) the current one (after removing from superview).
Mk12
I don't use IBOutlets, I don't use IB.
Mk12
I'm pretty sure that you are correct, if you only have one VC at a time then the view would never be unloaded. The most common case is when you use a navigation controller, and the views you navigated away from are still there...Even if you don't use IB, if you add subviews that you keep references for the same rule would apply - nil out the reference (though again this seems not to apply in your case).
Kendall Helmstetter Gelner
+2  A: 

-viewDidUnload is called whenever the viewcontroller's view property is set to nil, either manually or most commonly through didReceiveMemoryWarning:.

Rob Napier
+1  A: 

In addition to manually issuing a memory warning in the simulator, you can issue one programatically with

- (void)_simulateLowMemoryWarning {
  // Send out MemoryWarningNotification
  [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification
                                                      object:[UIApplication sharedApplication]];
  // Manually call applicationDidReceiveMemoryWarning
  [[[UIApplication sharedApplication] delegate] applicationDidReceiveMemoryWarning:[UIApplication sharedApplication]];
}

You can then cause this to happen every 5 seconds using a timer

static NSTimer *gLowMemoryTimer = nil;

- (void)stopLowMemoryTimer {
  [gLowMemoryTimer invalidate];
  gLowMemoryTimer = nil;
}

- (void)startLowMemoryTimer {
  if (gLowMemoryTimer) {
    [self _stopLowMemoryTimer];
  }
  gLowMemoryTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(_simulateLowMemoryWarning) userInfo:nil repeats:YES];
}
AlpacaJB