开发者

Sending memory warning in applicationWillResignActive

A few days ago I found a nice snippet on SO to test memory warnings by just sending a UIApplicationDidReceiveMemoryWarningNotification notification every 10 seconds or so.

I really liked the idea and adopted it to only send out the notification when the app switches into the background, since it makes it easier to clean up some memory since every UIViewController listens to this notification anyway (and performs some memory cleaning that I also benefit from).

Since I'm a lazy programmer I wondered if this kind of trick is allowed by Apple or not. Technically this not an private API usage and I even doubt that they find such things during testing, however, I'm not开发者_运维知识库 100% sure about this. The code that I'm using looks like this:

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Do some other stuff, unrelated to the question

    [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification object:application];
}


I had done the same thing in my App iFerien Deluxe and it went through the approval process without any problems. Personally I don't think, that this is a problem for Apple. But in my current app I'm trying to avoid this, because it looks a bit hacky, as you better had to manually free your memory in applicationWillResignActive.


It may be possible, but it's a little bad form.

You could easily write your own notification. Just open your project's precompiled header file (usually under "Other Sources" or "Supporting Files" and make sure it includes this #define.

#ifdef __OBJC__
    #define MyApplicationDidReceiveMemoryWarning @"myMemoryWarningString"
#endif

THe PCH is effectively included in every file you compile. Set up an NSTimer in applicationDidFInishLaunch:withOptions:

[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(sendMemoryNotification) userInfo:nil repeats:YES];

in the sendMemoryNotification method, just post the notification

-(void)sendMemoryNotification
{
    [[NSNotificationCenter defaultCenter] postNotification:MyApplicationDidReceiveMemoryWarning];
}

Any class that holds significant data register as an observer for the key in the NSNotificationCenter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜