本文介绍了如何创建本地自动释放池以节省内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

Apple说这对于节省内存是个好主意。在代码中看起来会是什么样?

解决方案

通常,您不需要创建自动释放池,因为系统关心这一点。但是,有时你需要这样做。它通常在大循环中。代码如下所示:

  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
int i;
for(i = 0; i< 1000000; i ++){
id object = [someArray objectAtIndex:i];
//对象
做一些if(i%1000 == 0){
[pool release];
pool = [[NSAutoreleasePool alloc] init];
}
}
[池发布];

自动释放池保存为堆栈:如果你创建一个新的自动释放池,它会被添加到堆栈顶部,每个自动释放消息都将接收器放入最顶层的池中。


Apple says that this is a good idea for saving memory. What would that look like in code?

解决方案

Usualy you don't need to create autorelease pool, because system cares about this. But, sometimes you need to do this. It's usualy in big loops. Code would look like this:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int i;
for (i = 0; i < 1000000; i++) {
  id object = [someArray objectAtIndex:i];
  // do something with object
  if (i % 1000 == 0) {
    [pool release];
    pool = [[NSAutoreleasePool alloc] init];
  }
}
[pool release];

Autorelease pools are kept as a stack: if you make a new autorelease pool, it gets added to the top of the stack, and every autorelease message puts the receiver into the topmost pool.

这篇关于如何创建本地自动释放池以节省内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 09:13