ARC的内存占用空间很大

Max*_*kov 2 memory-management objective-c autorelease automatic-ref-counting

我正在开发的应用程序使用ARC.我希望它处理大型文件,因此我不是整个文件加载,而是使用NSFileHandle readDataOfLength方法加载数据块.它发生在循环中,重复直到整个文件被处理:

- (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;

        ...

    }

    ...

}
Run Code Online (Sandbox Code Playgroud)

根据剖析器,没有内存泄漏; 但是,我的应用程序在处理文件时会占用大量内存.我猜 - 自动释放只在我处理完文件后才出现.我可以修改它而无需切换到手动内存管理吗?

Til*_*ill 9

使用自动释放池包装该循环中的代码.

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

readDataOfLength 返回自动释放的数据,因为你坚持在该循环内部及其方法,自动释放的数据在你的循环和封装方法完成之前不会被释放.

  • @golergka嗯?`@autoreleasepool {}`明确用于ARC:https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html (6认同)