statguy
statguy

Reputation: 1707

@autoreleasepool does not seem to drain pool

I am having memory issues in a larger application. I've simplified it to the code below. If I let the application run to completion, the memory drains, and therefore I don't have a true memory leak.

However, as it's running, each call to customLog: accumulates memory and the memory does not drain. So I added an @autoreleasepool block wrapping the call to log: and it still does not seem to drain. Is it possible I am not using @autoreleasepool correctly?

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    // Insert code here to initialize your application

    for (int i=0; i<100000; i++) {
        [Logger customLog:[NSString stringWithFormat:@"%i", i]];
    }

    for (int i=0; i<100000000; i++) {
        NSLog(@"X%i", i);
    }
}

Logger class:

- (void)customLog:(NSString *)logString
{
    @autoreleasepool {
        [self log:[[NSString alloc] initWithFormat:@"%@ %@:%d\t\t%s\t\%@", [[NSDate  date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S.%F" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]], [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, __FUNCTION__, logString]];
    }
}

Upvotes: 0

Views: 598

Answers (1)

rmaddy
rmaddy

Reputation: 318804

The autorelease pool is in the wrong place. You only clean up any autoreleased objects created inside the @autoreleasepool. But you create the thousands of temporary NSString objects outside of the autorelease pool so those aren't cleaned up until after the call to applicationDidFinishLaunching: is done.

Try:

for (int i=0; i<100000; i++) {
    @autoreleasepool {
        [Logger customLog:[NSString stringWithFormat:@"%i", i]];
    }
}

and remove the @autoreleasepool in the customLog: method.

Upvotes: 4

Related Questions