我必须将一个非常大的文件读入内存(读取时数据处理不是一个选项,我必须将整个文件放在设备内存中)。当设备内存不足时,我应该停止读取并向用户显示错误消息。
- (void)setUpStreamForFile:(NSString *)path {
_inputStream = [[NSInputStream alloc] initWithFileAtPath:path];
[_inputStream setDelegate:self];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
_didReceiveMemoryWarning = YES;
}];
[_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_inputStream open];
}
在我的流委托方法中,我_didReceiveMemoryWarning
每次都检查变量,如果它变为真则关闭流。
...
if (!_didReceiveMemoryWarning) {
if(!_tempData) {
_tempData = [NSMutableData data];
}
uint8_t buf[1024];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buf maxLength:1024];
if(len) {
[_tempData appendBytes:(const void *)buf length:len];
}
} else {
[self closeInputStream];
NSError *error error = [NSError errorWithDomain...];
[[NSNotificationCenter defaultCenter] postNotificationName:@"reading failed" object:error];
_didReceiveMemoryWarning = NO;
}
...
- (void)closeInputStream {
[_inputStream close];
[_inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
_inputStream = nil;
_tempData = nil;
}
读取工作在模拟器上工作,因为我在那里有足够的内存,但是在设备上,操作系统似乎在我收到通知之前杀死了应用程序(对于较小的文件,它也可以在设备上工作)。有谁知道这个问题的解决方案?