神秘的内存泄漏 - NSString自动释放问题

时间:2011-08-21 20:20:58

标签: objective-c ios

即使我在紧密循环中使用NSAutoreleasePool,下面方法中的以下行导致我获取内存警告并最终崩溃我的应用程序(通过注释掉该行,问题消失)。任何人都知道为什么会这样?

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(file 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];
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

我用php in_array()函数的Objective C等效替换了内部的“for”循环,内存问题消失了!

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

答案 1 :(得分:1)

break语句让你退出内部for循环,而不在NSAutoreleasePool上调用-drain。