bdunagan
fill the void

Posted
1 October 2008 @ 9am

Tagged
development

2 Comments

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.


2 Comments

Posted by
fill the void – FilePile: Finder for the iPhone
23 November 2008 @ 8pm

[...] environment required I manage the memory better. It was this path that led me to find the undocumented UIApplicationMemoryWarningNotification notification; using that allowed me to trigger low memory warnings in my application on the iPhone without [...]


Posted by
dave
1 February 2010 @ 9am

thank you so much, I’ve been struggling with the Memory Warning simulations on the real device for a couple of days but now it’s a piece of cake!
I couldn’t use the iPhone simulator and the Warning simulation there, since the problem was with the camera, which doesn’t run on the simulator.

Btw I had to change the name of the notification to UIApplicationDidReceiveMemoryWarningNotification, your event name didn’t trigger the didRecieveMemoryWarning in my controllers.


Leave a Comment