Max Yankov
Max Yankov

Reputation: 13297

Huge memory footprint with ARC

App I'm working on uses ARC. I wanted it to process large files, so instead of loading files as a whole, I'm loading chunks of data using NSFileHandle readDataOfLength method. It's happening inside a loop which repeats until the whole file is processed:

- (NSString*)doStuff { // called with NSInvocationOperation

    // now we open the file itself

    NSFileHandle *fileHandle =
    [NSFileHandle fileHandleForReadingFromURL:self.path
                                        error:nil];

    ...

    BOOL done = NO;
    while(!done) {

        NSData *fileData = [fileHandle readDataOfLength: CHUNK_SIZE];

        ...

        if ( [fileData length] == 0 ) done = YES;

        ...

    }

    ...

}

According to profiler, there are no memory leaks; however, my app eats a LOT of memory while it processes the file. My guess — autorelease comes only after I process the file. Can I fix it without switching to manual memory management?

Upvotes: 2

Views: 1195

Answers (1)

Till
Till

Reputation: 27597

Wrap the code within that loop with a autorelease pool.

while(!done) 
{
    @autoreleasepool
    {
        NSData *fileData = [fileHandle readDataOfLength: CHUNK_SIZE];
        ...
        if ( [fileData length] == 0 ) 
        {
            done = YES;
        }
        ...                
    }
};

readDataOfLength retuns autoreleased data and since you stick inside that loop and therefor its method, that autoreleased data that does not get released until your loop and the encapsulating method is done.

Upvotes: 9

Related Questions