//聯(lián)系人:石虎?QQ:1224614774?昵稱:嗡嘛呢叭咪哄
一、概念
1.內(nèi)存警告原理
*iphone下每個(gè)app可用的內(nèi)存是被限制的骂倘,如果一個(gè)app使用的內(nèi)存超過20M,則系統(tǒng)會向該app發(fā)送Memory?Warning消息巴席。收到此消息后历涝,app必須正確處理,否則可能出錯(cuò)或者出現(xiàn)內(nèi)存泄露。
?*app收到Memory?Warning后會調(diào)用:UIApplication::didReceiveMemoryWarning?->?UIApplicationDelegate::applicationDidReceiveMemoryWarning,然后調(diào)用當(dāng)前所有的viewController進(jìn)行處理荧库。因此處理的主要工作是在viewController堰塌。
?*?當(dāng)我們的程序在第一次收到內(nèi)存不足警告時(shí),應(yīng)該釋放一些不用的資源分衫,以節(jié)省部分內(nèi)存场刑。否則,當(dāng)內(nèi)存不足情形依然存在丐箩,ios再次向我們程序發(fā)出內(nèi)存不足的警告時(shí)摇邦,我們的程序?qū)籭OS kill掉。
*蘋果給每個(gè)應(yīng)用程序設(shè)置20M的內(nèi)存警告量屎勘,30M的閃退量,游戲會略微放款10~20M居扒,需要向系統(tǒng)申請概漱。
2.實(shí)現(xiàn)內(nèi)存警告有三種方法。
第一種:模擬器菜單:Hardware —> Simulate Memory Warning
第二種:用程序的方法實(shí)現(xiàn)喜喂,只需要一句代碼:
CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), (CFStringRef)@"UISimulatedMemoryWarningNotification",NULL,NULL,true);
? 第三種:這是私有的 API 方法:
?SEL memoryWarningSel = @selector(_performMemoryWarning);
? if?([[UIApplication sharedApplication] respondsToSelector:memoryWarningSel]) {
? ? ? [[UIApplication sharedApplication] performSelector:memoryWarningSel];
? }else?{
? ? ? NSLog(@"%@",@"Whoops UIApplication no loger responds to -_performMemoryWarning");
? }
或者:
?iOS中使用代碼模擬內(nèi)存警告
? [[UIApplication sharedApplication] performSelector:@selector(_performMemoryWarning)];
注意:最好只在測試的時(shí)候使用瓤摧,發(fā)布到App Store的時(shí)候不要將上面的代碼編譯進(jìn)去,使用這種沒有文檔化的方法有可能導(dǎo)致審核不通過玉吁,或者根本無法上傳照弥。
二、宏控制內(nèi)存警告測試
1.開關(guān)宏
#ifndef?__OPTIMIZE__
#define?OPEN_MEMORY_WARNING_TEST ?YES//打開內(nèi)存警告測試開關(guān)
#endif
2.調(diào)用私有API
-?(void)simulateMemoryWarning
? {
? ? ?if?(OPEN_MEMORY_WARNING_TEST?==?NO)?{
return;
? ? ? ? ?}
? ? ????[[UIApplication?sharedApplication]?_performMemoryWarning];
? }
3.在需要的地方調(diào)用
? [[MemoryWarningTest?sharedInstance]?simulateMemoryWarning];