富贵论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

手机号码,快捷登录

广告位招租qq41463402
查看: 10|回复: 0

[教程] iOS开发中怎么响应内存警告

[复制链接]

1万

主题

1245

回帖

5万

积分

巡抚

UID
21449
金钱
400 点
威望
0 点
贡献
19047 点
宣传
0 人
买家
0 元
卖家
0 元
注册时间
2017-8-15
最后登录
2024-7-26

活力无限勋章灌水天才勋章

发表于 2024-4-15 20:25 | 显示全部楼层 |阅读模式

好的应用应该在系统内存警告情况下释放一些可以重新创建的资源。在iOS中我们可以在应用程序委托对象、视图控制器以及其它类中获得系统内存警告消息。

1、应用程序委托对象

在应用程序委托对象中接收内存警告消息,需要重写applicationDidReceiveMemoryWarning:方法。AppDelegate的代码片段:

- (void)applicationDidReceiveMemoryWarningUIApplication *)application

{

NSLog(@”AppDelegate中调用applicationDidReceiveMemoryWarning:”);

}

2、视图控制器

在视图控制器中接收内存警告消息,需要重写didReceiveMemoryWarning方法。ViewController的代码片段:

- (void)didReceiveMemoryWarning

{

NSLog(@”ViewController中didReceiveMemoryWarning调用”);

[super didReceiveMemoryWarning];

//释放成员变量

[_listTeams release];

}

注意释放资源代码应该放在[super didReceiveMemoryWarning]语句下面。

3、其它类

在其它类中可以使用通知,在内存警告时候iOS系统会发出 UIApplicationDidReceiveMemoryWarningNotification通知,凡是在通知中心注册了 UIApplicationDidReceiveMemoryWarningNotification通知的类都会接收到内存警告通知。 ViewController的代码片段:

- (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

selectorselector(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调用

您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|富贵论坛 ( 琼ICP备2022019866号-1 )

GMT+8, 2024-7-27 13:55 , Processed in 0.122097 second(s), 32 queries .

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表