Quantcast
Viewing all articles
Browse latest Browse all 10

Debugging Magic: Auto Simulate iOS Memory Warnings

Full Source code: https://gist.github.com/956403

Problem:

You spend a lot of time and effort building your app, writing countless view controllers. You think it’s near perfect.

Then one of your beta testers (or customers, or app reviewers) finds a problem. You look into it and realize that it only happens after a low memory pressure warning.

You should have written your viewDidLoad to handle getting called after a low memory pressure warning, but you didn’t.

Wouldn’t it be great if you were forced to write your viewDidLoad implementation with low memory situations in mind? After all, out in the wild on real world devices, it’s very likely that sooner or later every single one of your view controllers will have to handle this.

Solution:

Add this code to your project and have your view controller inherit from BaseViewController instead of UIViewController. Every time viewWillAppear is called, the simulator will force a low memory warning:

- (void)simulateMemoryWarning
{
#if TARGET_IPHONE_SIMULATOR
  #ifdef DEBUG
    CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), (CFStringRef)@"UISimulatedMemoryWarningNotification", NULL, NULL, true);
  #endif
#endif
}

Finding the Solution

I found myself in this pattern one too many times. I finally decided to find a solution.

The iOS Simulator has the menu Hardware -> Simulate Memory Warning

But I wasn’t going to select that menu item every time you test to see if something works.

I embarked on figuring out how this menu item works.

I looked through the UIKit framework binary (/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks/UIKit.framework/UIKit) searching for words like memory and warning.

I put breakpoints in gdb trying to find what message is sent. I read the NSNotification docs. After many dead ends I discovered the name of the notification: UISimulatedMemoryWarningNotification and that I needed to use CFNotificationCenter to send the message.

I’ve tried this out on a couple of projects and it has forced me to think about low memory situations from day one.

Full Source code: https://gist.github.com/956403

Image may be NSFW.
Clik here to view.
Tweet This!
Image may be NSFW.
Clik here to view.
Hacker News
Image may be NSFW.
Clik here to view.
Share on Facebook


Viewing all articles
Browse latest Browse all 10

Trending Articles