开发者

Mysterious Memory Leak - NSString Autorelease Issue

Even though I'm using NSAutoreleasePool in a tight loop, the following line in the method below is causing me to get memory warnings and ultimately crashing my app (by commenting out that line, the problem goes away). Anyone have an idea why this is the case?

filepath = [docpath stringByAppendingPathComponent:file];

-(void)fileCleanup
{
    NSString *documentspath = [AppSession documentsDirectory];
    NSString *docpath = [documentspath stringByAppendingPathComponent:@"docs"];
    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSArray *files = [filemanager subpathsOfDirectoryAtPath:docpath error:NULL];
    NSLog(@"fileCleanup");
    if(files != nil && [files count] > 0)
    {
        BOOL deletefile;
        NSString *filepath;
        NSAutoreleasePool *readPool;
        NSString *testfile;
        NSString *file;

        for(f开发者_如何学运维ile in files) 
        {
            deletefile = YES;

            for (testfile in allFiles) {
                readPool = [[NSAutoreleasePool alloc] init];

                //line below is causing memory leak!
                filepath = [docpath stringByAppendingPathComponent:file];
                //if([filepath isEqualToString:testfile])
                //{
                   // deletefile = NO;
                   // break;
                //} 
                [readPool drain];
            }

            if(deletefile)
            {
                [self logText:[@"\nD: " stringByAppendingString:[@"docs/" stringByAppendingPathComponent:file]]];
                [filemanager removeItemAtPath:[docpath stringByAppendingPathComponent:file] error:NULL];
            }
        }
    }


I replaced the inner "for" loop with the Objective C equivalent of the php in_array() function and the memory issues disappeared!

    NSUInteger matchint = [allFiles indexOfObject:[docpath stringByAppendingPathComponent:file]];
    if(matchint != NSNotFound)
        deletefile = NO;


The break statement was dropping you out of your inner for loop without calling -drain on the NSAutoreleasePool.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜