1.當(dāng)iOS系統(tǒng)內(nèi)存不足,會發(fā)出內(nèi)存警告的通知。
首先調(diào)用的是 AppDelegate 里重新的內(nèi)存警告代理方法
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
NSLog(@"內(nèi)存在警告時會AppDelegate中applicationDidReceiveMemoryWarning調(diào)用");
}
2.可以在控制器里注冊內(nèi)=內(nèi)存警告的通知
//控制器注冊警告通知
-(void) regMemoryWarning{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(handleMemoryWarning)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
//警告通知回調(diào)方法
-(void) handleMemoryWarning
{
NSLog(@"ViewController中handleMemoryWarning調(diào)用");
}
//控制器自動調(diào)用的內(nèi)存警告方法(如果控制器注冊了內(nèi)存警告通知,那么,當(dāng)程序發(fā)生內(nèi)存警告的時候菩颖,會優(yōu)先調(diào)用通知方法,后調(diào)用控制器的)didReceiveMemoryWarning方法)为障。
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
NSLog(@"viewcontroller 的didReceiveMemoryWarning調(diào)用");
}
總結(jié):
當(dāng)發(fā)生內(nèi)存警告的時候就會接收通知晦闰,調(diào)用通知方法,進(jìn)行處理響應(yīng)的事情鳍怨。
內(nèi)存警告的優(yōu)先級調(diào)用順序是 AppDelegate的- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application方法 >控制器的UIApplicationDidReceiveMemoryWarningNotification通知方法>控制器的didReceiveMemoryWarning方法
2.怎么模擬iOS內(nèi)存警告呢呻右?
(1)真機(jī)模擬內(nèi)存警告
SEL sel = NSSelectorFromString([@"_perform" stringByAppendingString:@"MemoryWarning"]); // Private API
assert([[UIApplication sharedApplication] respondsToSelector:sel]);
[[UIApplication sharedApplication] performSelector:sel];
(2)模擬器的模擬內(nèi)存警告
在好多大牛的帖子里看到的是這樣的操作:模擬器菜單:Hardware-》Simulate Memory Warning
當(dāng)是我在操作的時候就是找不到后面的選項Simulate Memory Warning
當(dāng)是我的心里一萬個不爽啊P(我當(dāng)時用的是Xcode9.4)
后來我在Debug 的選項里看到了后面的 Simulate Memory Warning選擇声滥,所以我的操作是Debug-》Simulate Memory Warning
就是這樣操作,就可以檢驗上面所寫的當(dāng)程序發(fā)生內(nèi)存警告的時候确徙,調(diào)用方法的順序?qū)崿F(xiàn)了醒串。
3.當(dāng)內(nèi)存發(fā)生警告的時候,我們應(yīng)該做什么樣的操作呢鄙皇?
(1)當(dāng)我們在下載高清的圖片和視頻的時候芜赌,是很容易發(fā)生內(nèi)存警告的,如果使用了SDWebImage框架,使用如下代碼,可以有效的減少內(nèi)存:
[[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];//清除內(nèi)存中通過SDWebImage框架下載的圖片,建議在收到內(nèi)存警告時在調(diào)用
(2) //在收到內(nèi)存警告時,控制器里調(diào)用以下代碼:
if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
if (self.isViewLoaded && !self.view.window){
//釋放其他可復(fù)現(xiàn)的資源&&保存數(shù)據(jù)
self.view = nil;//目的是再次進(jìn)入時能夠重新加載調(diào)用viewDidLoad函數(shù)伴逸。
}
}
iOS 給每個應(yīng)用的緩存數(shù)據(jù)是 20M 缠沈,這個我也是從大量的帖子里,看到的答案错蝴,有待考證和探討洲愤。希望大家來一起討論和研究!