170
技術社區[雲棲]
iOS開發那些事-響應內存警告
好的應用應該在係統內存警告情況下釋放一些可以重新創建的資源。在iOS中我們可以在應用程序委托對象、視圖控製器以及其它類中獲得係統內存警告消息。1、應用程序委托對象
在應用程序委托對象中接收內存警告消息,需要重寫applicationDidReceiveMemoryWarning:方法。AppDelegate的代碼片段:
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
NSLog(@”AppDelegate中調用applicationDidReceiveMemoryWarning:”);
}
2、視圖控製器
在視圖控製器中接收內存警告消息,需要重寫didReceiveMemoryWarning方法。ViewController的代碼片段:
- (void)didReceiveMemoryWarning
{
NSLog(@”ViewController中didReceiveMemoryWarning調用”);
[super didReceiveMemoryWarning];
//釋放成員變量
[_listTeams release];
}
注意釋放資源代碼應該放在[super didReceiveMemoryWarning]語句下麵。
3、其它類
在其它類中可以使用通知,在內存警告時候iOS係統會發出UIApplicationDidReceiveMemoryWarningNotification通知,凡是在通知中心注冊了
UIApplicationDidReceiveMemoryWarningNotification通知的類都會接收到內存警告通知。ViewController的代碼片段:
- (void)viewDidLoad
{
[super viewDidLoad];
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"team"
ofType:@"plist"];
//獲取屬性列表文件中的全部數據
NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];
self.listTeams = array;
[array release];
//接收內存警告通知,調用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調用
最後更新:2017-04-04 07:03:45