好的應用應該在系統(tǒng)內(nèi)存警告情況下釋放一些可以重新創(chuàng)建的資源。在iOS中我們可以在應用程序委托對象、視圖控制器以及其它類中獲得系統(tǒng)內(nèi)存警告消息。
1、應用程序委托對象
在應用程序委托對象中接收內(nèi)存警告消息,需要重寫applicationDidReceiveMemoryWarning:方法。AppDelegate的代碼片段:
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { NSLog(@”AppDelegate中調(diào)用applicationDidReceiveMemoryWarning:”); }
2、視圖控制器
在視圖控制器中接收內(nèi)存警告消息,需要重寫didReceiveMemoryWarning方法。ViewController的代碼片段:
- (void)didReceiveMemoryWarning { NSLog(@”ViewController中didReceiveMemoryWarning調(diào)用”); [super didReceiveMemoryWarning]; //釋放成員變量 [_listTeams release]; }
注意釋放資源代碼應該放在[super didReceiveMemoryWarning]語句下面。
3、其它類
在其它類中可以使用通知,在內(nèi)存警告時候iOS系統(tǒng)會發(fā)出 UIApplicationDidReceiveMemoryWarningNotification通知,凡是在通知中心注冊了 UIApplicationDidReceiveMemoryWarningNotification通知的類都會接收到內(nèi)存警告通知。 ViewController的代碼片段:
- (void)viewDidLoad { [super viewDidLoad]; NSBundle *bundle = [NSBundle mainBundle]; NSString *plistPath = [bundle pathForResource:@"team" ofType:@"plist"]; //獲取屬性列表文件中的全部數(shù)據(jù) NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath]; self.listTeams = array; [array release]; //接收內(nèi)存警告通知,調(diào)用handleMemoryWarning方法處理 NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(handleMemoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; } //處理內(nèi)存警告 -(void) handleMemoryWarning { NSLog(@”ViewController中handleMemoryWarning調(diào)用“); }
我們在viewDidLoad方法中注冊UIApplicationDidReceiveMemoryWarningNotification消 息,接收到報警信息調(diào)用handleMemoryWarning方法。這些代碼完全可以寫在其它類中,在ViewController中重寫 didReceiveMemoryWarning方法就可以了,本例這是示意性介紹一下 UIApplicationDidReceiveMemoryWarningNotification報警消息。
內(nèi)存警告在設備上出現(xiàn)并不是經(jīng)常的,一般我們沒有辦法模擬,但模擬器上有一個功能可以模擬內(nèi)存警告,啟動模擬器,選擇模擬器菜單硬件→模擬內(nèi)存警告,這個時候我們會在輸出窗口中看到內(nèi)存警告發(fā)生了。
2012-11-06 16:49:16.419 RespondMemoryWarningSample[38236:c07] Received memory warning.
2012-11-06 16:49:16.422 RespondMemoryWarningSample[38236:c07] AppDelegate中調(diào)用applicationDidReceiveMemoryWarning:
2012-11-06 16:49:16.422 RespondMemoryWarningSample[38236:c07] ViewController中handleMemoryWarning調(diào)用
2012-11-06 16:49:16.423 RespondMemoryWarningSample[38236:c07] ViewController中didReceiveMemoryWarning調(diào)用