bdunagan

fill the void - bdunagan

01 Oct 2008
Triggering didReceiveMemoryWarning on the iPhone

Now that the NDA is lifted, I can post a handy iPhone dev trick. Craig Hockenberry posted a twitter a while back recommending you trigger didReceiveMemoryWarning in your app to work out any memory issues. And being able to trigger that warning in the iPhone Simulator, rather than on the device, would make debugging easier.

However, getting your warning to propagate through your objects like a real warning does is a bit tricky. You have to use an undocumented notification message: UIApplicationMemoryWarningNotification. You can wrap it in a method like so.

- (void)triggerMemoryWarning
{
    // Post 'low memory' notification that will propagate out to controllers
    // Note: UIApplicationDidReceiveMemoryWarningNotification doesn't work for some reason.
    [[NSNotificationCenter defaultCenter] postNotificationName:
            @"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
}

Putting that method on a timer allows you to trigger a low memory warning throughout your application at a regular interval. For some reason, it doesn’t trigger the warning in your base controller, but you can easily add that class as an observer to that notification.

[[NSNotificationCenter defaultCenter] addObserver:[[UIApplication sharedApplication] delegate]
                                                       selector:@selector(applicationDidReceiveMemoryWarning:) 
                                                       name:@"UIApplicationMemoryWarningNotification" 
                                                       object:nil];

This process should allow you to trigger a didReceiveMemoryWarning notification throughout your iPhone application just like a real warning. The fact that it’s undocumented is okay because it’s only for testing purposes.

Previous LinkedIn Twitter GitHub Email Next