My app sometimes reads data, uses it, then might need to read it again later. I noticed that if I read the data once it gets released, but if I happen to read it again it never gets released.
Why is the data not released if read again?
Code:
#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
Try using dataWithContentsOfFile:options:error
with option:
NSDataReadingMappedIfSafe
A hint indicating the file should be mapped into virtual memory, if possible and safe.
Although the description of dataWithContentsOfFile
does not indicate, not using the options
will likely result in data being retained otherwise.
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:.