十三年专注于网站建设与互联网应用开发,低调、有情怀的网络应用服务商!
南昌百恒科技微信公众号 扫一扫关注
tel-icon全国服务热线:400-680-9298,0791-88117053
扫一扫关注百恒科技微信公众号

ios应用内存不足时如何获得内存警告消息?

百恒 2017-11-08 14:45:30 3367
       好的应用应该在系统内存警告的情况下释放一些可以重新创建的资源。在ios中,我们可以在应用程序委托对象、视图控制器以及其他类中获得系统内存警告消息的。那么具体如何获得呢?下面南昌APP开发公司小编就来为大家介绍一下。 

       1、应用程序委托对象 
       在应用程序委托对象中接收内存警告消息,需要重写applicationDidReceiveMemoryWarning:,方法如下:
       - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application 
       {     
       NSLog(@"AppDelegate中调用applicationDidReceiveMemoryWarning:"); 
       } 

       2、视图控制器
       在视图控制器中接收内存警告消息,需要重写didReceiveMemoryWarning方法,具体方法如下:
       - (void)didReceiveMemoryWarning 
       {     
       NSLog(@"ViewController中didReceiveMemoryWarning调用");     
       [super didReceiveMemoryWarning];     
       //释放成员变量     
       [_listTeams release]; 
       } 
       注意,释放资源代码应该放在[super didReceiveMemoryWarning]语句后面。 

       3、其他类 
       在其他类中可以使用通知。在发生内存警告时,iOS系统会发出UIApplicationDidReceiveMemoryWarning- Notification通知,凡是在通知中心注册了该通知的类都会接收到内存警告通知,具体方法如下: 
       - (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方法就可以了。

       在此,南昌APP开发公司小编要提醒大家的是,内存警告在设备上并不经常出现,一般我们没有办法模拟,但模拟器上有一个功能可以模拟内存警告。启动模拟器,选择“硬件”→“模拟内存警告”模拟器菜单,这时我们会在输出窗口中看到内存警告发生了,具体如下所示: 

       2017-11-07 15:58:51.032 MemoryLeakSample[1396:41574] Received memory warning. 
       2017-11-07 15:58:51.033 MemoryLeakSample[1396:41574] AppDelegate中调用applicationDidReceiveMemoryWarning: 
       2017-11-07 15:58:51.034 MemoryLeakSample[1396:41574] ViewController中handleMemoryWarning调用 
       2017-11-07 15:58:51.034 MemoryLeakSample[1396:41574] ViewController中didReceiveMemoryWarning调用

       以上便是小编为大家介绍的关于在ios中获得内存警告的几个途径,这样用户体验就更好了。百恒网络专注于APP开发、小程序开发等服务,十多年丰富经验,如有需要,我们随时为您效劳!
400-680-9298,0791-88117053
扫一扫关注百恒网络微信公众号

欢迎您的光顾,我们将竭诚为您服务×

售前咨询 售前咨询
 
售前咨询 售前咨询
 
售前咨询 售前咨询
 
售前咨询 售前咨询
 
售前咨询 售前咨询
 
售后服务 售后服务
 
备案专线 备案专线
 
售后服务 售后服务
 
×