Objective-C memory management regarding big loops
I have a really large loop in my program, and I use a lot of temporary and instance variables. As my loop keeps running, the program uses up more a开发者_JAVA技巧nd more memory until it crashes. Can I get some advice on how to do correct memory management in this situation? My main question is, why is the following code wrong?
Here is the code that is causing the leak:
(void) processTrackValues:(NSMutableArray*) tags {
NSImage* trackArt = [tags objectAtIndex:5]; NSMutableArray* tempArtArray = [[NSMutableArray alloc] init]; [tempArtArray addObject:trackArt]; [tempArtArray release]; }
I also tried:
(void) processTrackValues:(NSMutableArray*) tags {
NSImage* trackArt = [tags objectAtIndex:5]; NSMutableArray* tempArtArray = [[NSMutableArray alloc] init]; [tempArtArray addObject:trackArt]; [trackArt release]; [tempArtArray release]; }
Adam's answer is correct. In pseudo code:
unsigned int iters = 0;
NSAutoreleasePool *p = nil;
while(1) {
if (!p) p = [[NSAutoreleasePool alloc] init];
... do stuff here ...
if ( iters == 1000) {
iters = 0;
[p drain];
p = nil;
}
}
Re-using temporary objects is generally a waste of time and rife with fragility.
Frankly, you should probably just do the autorelease pool dance once per every iteration through the loop and ignore any silly counters and the like until you have instrumented proof that there is overhead otherwise.
Something like:
NSAutoreleasePool *p = nil;
while(1) {
p = [[NSAutoreleasePool alloc] init];
... do stuff here ...
[p drain];
}
You could try to reuse your temporary objects or set up your own AutoReleasePool for those objects and release it every 1000 iterations or so.
精彩评论