1

假设我有这样的代码:

NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
for(unsigned int i=0;i<10;i++)
{
    NSDate* date=[[NSDate alloc]init];
}
[pool drain];

请注意,此代码仅用于显示我可以做什么,它是对我通常做的事情的简化。因此,在每次迭代中,都会分配并初始化一个新的 NSDate。NSAutoreleasePool 是否将它们全部耗尽,或者我是否必须以这种方式在循环中添加 NSAutoreleasePool:

for(unsigned int i=0;i<10;i++)
{
    NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
    NSDate* date=[[NSDate alloc]init];
    [pool drain];
}

?
另外,我的书(mac os x 的可可编程)没有提到 NSAutoreleasePool,它只是这样使用它:

@autoreleasepool
{
    <code>
}

我已经读到这种方式比使用 NSAutoreleasePool 更有效,但是如果我使用它,我会收到一个语法错误:
“程序中出现意外的 '@'”
为什么会这样?

我试过这样修改代码:

NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
for(unsigned int i=0;i<10;i++)
{
    NSDate* date=[[NSDate alloc]init];
    [date autorelease];
}
[pool drain];

那是对的吗?我认为保留了 10 个不同的对象(计数为 1),然后添加到自动释放池中。我没有内存泄漏吗?有没有办法用 gdb 检查这个对象计数?

4

2 回答 2

5

当你分配/初始化一个类时,返回的实例通常不会被自动释放。所以,不,在那个例子中,根本不需要自动释放池。

通常,当您有可量化的性能问题表明需要自动释放池时,您应该只在代码中添加自动释放池。不要解决你没有的问题。

如果@autoreleasepool不起作用,那是因为您使用的是较旧的编译器。

于 2012-04-06T21:34:25.697 回答
0

来自苹果文档

If you write a loop that creates many temporary objects.
You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application.

所以如果@Ramy 使用不是更好:

for(unsigned int i=0;i<10;i++)
{
    NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
    NSDate* date=[[NSDate alloc]init];
    [date autorelease];
    [pool drain];
}
于 2013-06-12T04:54:44.690 回答