Objective-C, NSMutableData 未发布

Objective-C, NSMutableData not released

我的应用有时会读取数据、使用数据,然后可能需要稍后再次读取。我注意到,如果我在数据发布后读取它,但如果我碰巧再次读取它,它就永远不会被发布。

为什么再次读取数据没有释放?

代码:

#import "AppDelegate.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self readData]; // read one
    NSLog(@"read1");
    sleep(1);
    [self readData2];
}

- (void)readData2 {
    [self readData]; // read two
    NSLog(@"read2");
}

- (void)readData {
    __block NSMutableData *data = [NSMutableData dataWithContentsOfFile:@"test"]; // file is 125 MB
    NSUInteger size = [data length];
        for (NSUInteger i = 0; i < size; i++) {
            // do stuff
        }
        return;
}
@end

尝试使用 dataWithContentsOfFile:options:error 和选项:

NSDataReadingMappedIfSafe

A hint indicating the file should be mapped into virtual memory, if possible and safe.

虽然dataWithContentsOfFile的描述中没有说明,但不使用options可能会导致数据被保留,否则。

dataWithContentsOfFile

This method is equivalent to dataWithContentsOfFile:options:error: with no options. If you need to know what was the reason for failure, use dataWithContentsOfFile:options:error:.