Cocoa NSAutoreleasePool

Autorelease pools are extremely convenient for not having to worry about memory allocation and freeing the allocated memory, similar to the Newton days with its garbage collection. A problem that I’ve been aware of with autorelease pools, but promptly forget all the time is that if you are in a tight loop and keep creating autoreleased items, you’re going to run out of memory and crash. For instance, in the following block of code, without even realizing it, a new autoreleased NSDate is being created once every tenth of a second. If you are processing data for say 3 minutes, you have created 1800 of these that aren’t being released.

while (running)
{
	[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.10]];
}

Now that I’ve thought about this, 1800 doesn’t sound all that bad, however, if you keep doing this without giving the OS a chance to do the autorelease cleanup, you’ll run out of memory. A better way of doing this is:

while (running)
{
	NSDate *newDate = [[NSDate alloc] initWithTimeIntervalSinceNow:0.10];
	[NSThread sleepUntilDate:newDate];
	[newDate release];
}

This way you won’t have anything lying around. Hopefully this will save a crash or two and lots of time scratching my head figuring out why it is crashing when I can’t reproduce the problem.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.