Cocoa Auto-repeat in a loop
(I read Apple's memory management guide as well as other help on memory management here, but I'm still confused about the following)
What should I do to manage memory with convenience methods in a loop? Whether to explicitly create the autoresource pool and then merge it. Or is it all automatic?
eg.
for (i=0; i<numFilePaths; i++) {
// ...
NSString *componentString = [someString lastPathComponent];
// ...
}
In this example, I am repeatedly getting a newline from lastPathComponent. Ignoring for a moment about bad manners in the same thing, how should I handle this memory management situation?
'componentString' is not stored at all, it only has a lifespan inside the loop and is just used for comparison with other strings. Thanks for any help.
a source to share
The autoresist pool only expires when the startup cycle ends, usually at the end of the method when control is returned to the user. If you run into a loop many times that will create a lot of auto-executing objects (which will accumulate in memory until your method ends), you may need to create a local autoresource pool and merge it yourself.
You can create and merge a local autoresource pool by simply creating and releasing a new one.
for (i=0; i<10000; i++) {
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
NSString *aString = [NSString string];
[pool drain];
}
You have probably achieved performance if you create and release too many pools, so you can check a certain number of iterations (say every 100 cycles or so) to create and release the pools. There is no set number, so you'll have to play around a bit.
UPDATE: Updated [pool release]
to [pool drain]
to support future garbage collection compatibility as recommended by Marc Charbonneau.
a source to share