iPhone - How to deal with low memory conditions

吃可爱长大的小学妹 提交于 2019-12-06 06:09:09

My idea is that two methods are called when an app receives a low memory warning:

didReceiveMemoryWarning // in your NSObjects

and

applicationDidReceiveMemoryWarning // in your app delegate

then, if you want to free memory, these are the methods to consider.

As regards what you can do in there... Well... Think about what Xcode suggests:

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

Seemingly, the best choise will be freeing any object not seen by the user and/or not in use, or any cached data that you can recreate later. Do not touch your GUI: if you close it or part of it your app becomes unusable and the user disappointed.

Regarding your 2 scenarios, I see a possible mistake in considering what memory warning are for. They are a way to treat an emergency and not the normal way to manage memory. Developpers must think of a good memory architecture and save data whenever possible.

In scenario 1, save your data when the app is sent to background.

applicationDidEnterBackground

In scenario 2, save your data when a new view is opened.

Hope this makes sense...

Consider the alternatives to your scenarios. Your app could be killed if it does not free enough memory, which would be even more jarring to the user. One might choose potentially flickering the current display over losing the user's valuable data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!