1

如果我创建一个带有回调的线程,例如..

NSAutoreleasePool* pool = [NSAutoreleasePool alloc] init];
while(1) {
   //Process Stuff
}
[pool release];

我假设任何自动释放的东西都不会真正被释放,因为池永远不会被耗尽。我可以改变周围的事情是这样的:

while(1) {
   NSAutoreleasePool* pool = [NSAutoreleasePool alloc] init];
   //Process Stuff
   [pool release];
}

但是这么频繁地分配/删除似乎有点浪费。有没有办法可以留出一块内存并在池满时释放它?

4

2 回答 2

7

不用担心,因为Autorelease 是 Fast。你的第二个选项很好。@autoreleasepool { }事实上,在 ARC 中,由于新的语法,除了这两个选项之外很难做任何事情。

于 2011-08-25T17:37:07.017 回答
1

如果您在循环的每次迭代中分配大量自动释放的内存,那么为每次迭代创建和释放一个新池是正确的做法,以防止内存堆积。

如果您不生成太多自动释放的内存,那么它不会有好处,您只需要外部池。

如果您分配了足够的内存以使单次迭代无关紧要,但在您完成时还有很多,那么您可以每 X 次迭代创建和释放池。

#define IterationsPerPool 10
NSAutoreleasePool* pool = [NSAutoreleasePool new];
int x = 0;
while(1) {
   //Process Stuff
   if(++x == IterationsPerPool) {
      x = 0;
      [pool release];
      pool = [NSAutoreleasePool new];
   }
}
[pool release];

* 你需要确定什么对你自己很重要

于 2011-08-25T17:44:49.823 回答