现在的位置: 首页 > 综合 > 正文

善用 NSAutoreleasePool 节约宝贵内存

2013年09月04日 ⁄ 综合 ⁄ 共 612字 ⁄ 字号 评论关闭

autorelease自动释放内存,并不会立即把内存释放掉,而是要等到下一个事件周期才会释放掉。问题是一些资源我们不得不使用autorelease类型,比如作为函数的返回值,而且系统api及项目是的大部分也都是这么做的,如果全都依靠我们手动释放很容易造成内存泄漏。

01 for (int i = 0; i <= 10000; i ++) {
02  
03        //创建一个自动释放池
04  
05         NSAutoreleasePool *pool = [NSAutoreleasePool new];
06  
07         NSString *filePath = [[NSBundle mainBundle] pathForResource:@"hf" ofType:@"PNG"];
08  
09         UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
10  
11         UIImage *scalimage = [image imageByScalingAndCroppingForSize:CGSizeMake(320, 640)];
12  
13         [image release];
14  
15        //将自动释放池内存释放,它会同时释放掉上面代码中产生的临时变量image2
16  
17         [pool drain];
18  
19     }


抱歉!评论已关闭.