西西軟件下載最安全的下載網(wǎng)站、值得信賴的軟件下載站!

首頁編程開發(fā)其它知識 → iOS開發(fā)中怎么響應(yīng)內(nèi)存警告

iOS開發(fā)中怎么響應(yīng)內(nèi)存警告

相關(guān)軟件相關(guān)文章發(fā)表評論 來源:西西整理時間:2013/2/11 9:16:29字體大小:A-A+

作者:西西點擊:0次評論:1次標簽: iOS開發(fā)

好的應(yīng)用應(yīng)該在系統(tǒng)內(nèi)存警告情況下釋放一些可以重新創(chuàng)建的資源。在iOS中我們可以在應(yīng)用程序委托對象、視圖控制器以及其它類中獲得系統(tǒng)內(nèi)存警告消息。

1、應(yīng)用程序委托對象

在應(yīng)用程序委托對象中接收內(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];

}

注意釋放資源代碼應(yīng)該放在[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)存警告在設(shè)備上出現(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)用

    相關(guān)評論

    閱讀本文后您有什么感想? 已有人給出評價!

    • 8 喜歡喜歡
    • 3 頂
    • 1 難過難過
    • 5 囧
    • 3 圍觀圍觀
    • 2 無聊無聊

    熱門評論

    最新評論

    發(fā)表評論 查看所有評論(1)

    昵稱:
    表情: 高興 可 汗 我不要 害羞 好 下下下 送花 屎 親親
    字數(shù): 0/500 (您的評論需要經(jīng)過審核才能顯示)
    推薦文章

    沒有數(shù)據(jù)