1、应用程序委托对象
在应用程序委托对象中接收内存警告消息,需要重写applicationDidReceiveMemoryWarning:方法。AppDelegate的代码片段:
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
NSLog(@”AppDelegate中调用applicationDidReceiveMemoryWarning:”);
}
2、视图控制器
在视图控制器中接收内存警告消息,需要重写didReceiveMemoryWarning方法。ViewController的代码片段:
- (void)didReceiveMemoryWarning
{
NSLog(@”ViewController中didReceiveMemoryWarning调用”);
[super didReceiveMemoryWarning];
//做一些事情
}
其他代码应该放在[super didReceiveMemoryWarning]语句下面。
3、其它类
在其它类中可以使用通知,在内存警告时候iOS系统会发出UIApplicationDidReceiveMemoryWarningNotification通知,凡是在通知中心注册了
- (void)viewDidLoad
{
[super viewDidLoad];
//接收内存警告通知,调用handleMemoryWarning方法处理
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(handleMemoryWarning)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
//处理内存警告
-(void) handleMemoryWarning
{
NSLog(@”ViewController中handleMemoryWarning调用“);
}
我们在viewDidLoad方法中注册UIApplicationDidReceiveMemoryWarningNotification消息,接收到报警信息调用handleMemoryWarning方法。这些代码完全可以写在其它类中,在ViewController中重写didReceiveMemoryWarning方法就可以了,本例这是示意性介绍一下UIApplicationDidReceiveMemoryWarningNotification报警消息。
内存警告在设备上出现并不是经常的,一般我们没有办法模拟,但模拟器上有一个功能可以模拟内存警告,启动模拟器,选择模拟器菜单硬件→模拟内存警告,这个时候我们会在输出窗口中看到内存警告发生了。
2012-11-06 16:49:16.419 RespondMemoryWarningSample[38236:c07] Received memory warning.
2012-11-06 16:49:16.422 RespondMemoryWarningSample[38236:c07] AppDelegate中调用applicationDidReceiveMemoryWarning:
2012-11-06 16:49:16.422 RespondMemoryWarningSample[38236:c07] ViewController中handleMemoryWarning调用
2012-11-06 16:49:16.423 RespondMemoryWarningSample[38236:c07] ViewController中didReceiveMemoryWarning调用