Question

Let's say that I have a code like this:

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

Please note that this code has only the purpose of showing what I could be doing, it's a simplification of what I usually do. So in each iteration a new NSDate is allocated and initialized. Does the NSAutoreleasePool drain them all, or do I have to add the NSAutoreleasePool in the loop this way:

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

?
Also, my book (cocoa programming for mac os x) doesn't mention the NSAutoreleasePool, it just use it this way:

@autoreleasepool
{
    <code>
}

I have read that this way is more efficient than using the NSAutoreleasePool, but if I use it I get a syntax error:
"Unexpected '@' in program"
Why this?

I have tried modifying the code this way:

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

Is that correct? I think that 10 different objects are retained (count to 1), then added to the autorelease pool. Am I not having memory leaks? Is there a way to check with gdb this object count?

Was it helpful?

Solution

When you alloc/init a class, the returned instance generally will not be autoreleased. So, no, in that example, the autorelease pool isn't needed at all.

In general, you should only sprinkle autorelease pools in your code when you have quantifiable performance problem that indicates that it is needed. Don't fix problems you don't have.

If @autoreleasepool isn't working, it is because you are working with an older compiler.

OTHER TIPS

from apple docs

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.

so isn't it better if @Ramy uses:

for(unsigned int i=0;i<10;i++)
{
    NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
    NSDate* date=[[NSDate alloc]init];
    [date autorelease];
    [pool drain];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top