佳为好友

转:让代码自动发送内存不足的消息

转:http://idevrecipes.com/2011/05/04/debugging-magic-auto-simulate-memory-warnings/

日期:120103
[自:亲自测试:该消息只能在ios4上使用,在ios5上则不会发送内存不足的消息。]
[自:这种方法能够完全测试内存不足情况下的问题,避免遗忘,推荐。]

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:

1- (void)simulateMemoryWarning
2{
3#if TARGET_IPHONE_SIMULATOR
4  #ifdef DEBUG
5    CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), (CFStringRef)@"UISimulatedMemoryWarningNotification"NULLNULLtrue);
6  #endif
7#endif
8}

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

+++++

posted on 2012-12-29 19:51 佳为好友 阅读(223) 评论(0)  编辑 收藏 引用 所属分类: 非UI


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2012年12月>
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345

留言簿(1)

随笔分类

搜索

最新评论

评论排行榜