當前位置:編程學習大全網 - 源碼下載 - ios的內存警告怎麽處理

ios的內存警告怎麽處理

轉載 想要很好的應用ios開發技術,其中怎樣響應內存警告是很重要的,使用的方法決定妳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)viewDidLoa

{

[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調用

多看多做多練習是學習語言必須經歷的過程,學習不是壹朝壹夕的事情,只有恒之以衡的堅持才能帶來成功。達內希望以上的ios教程能給大家帶來幫助。

  • 上一篇:駕校網源代碼
  • 下一篇:html5學習工具有哪些
  • copyright 2024編程學習大全網