Enable memory warnings in the iOS simulator to catch crash issues

One common crash issue that’s tough to catch during iOS development of UIViewControllers is the unloading and re-loading of views due to memory warnings.

The viewDidUnload method ONLY gets called when a memory warning comes in, NOT as part of the regular view lifecycle. During development it’s likely you may never get a memory warning, so viewDidUnload followed by viewDidLoad on the same controller may never get exercised. Whereas in the real-world on your users devices you want to be confident that viewDidLoad -> Memory Warning -> viewDidUnload -> viewDidLoad works as expected on a single instance of a UIViewController.

We like to have memory warnings firing regularly when we’re running in the simulator. We trigger memory warnings every 10 seconds so that as we work in the simulator we catch these kinds of issues early and often. The solution we came up with is based on this stackoverflow post. We add the following code to our *AppDelegate.m:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {        
    [self issuePeriodicLowMemoryWarningsInSimulator];
    // ...
}

- (void)issuePeriodicLowMemoryWarningsInSimulator {
    #if (TARGET_IPHONE_SIMULATOR)
    [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification object:[UIApplication sharedApplication]];
    [[[UIApplication sharedApplication] delegate] applicationDidReceiveMemoryWarning:[UIApplication sharedApplication]];
    [self performSelector:@selector(issuePeriodicLowMemoryWarningsInSimulator) withObject:nil afterDelay:10];    
    #endif
}

Leave a Reply