我必须将一个非常大的文件读入内存(读取数据时不能进行数据处理,我必须将整个文件保存在设备内存中)。当设备内存不足时,我应该停止读取并向用户显示错误消息。
- (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];
}
在我的流委托(delegate)方法中,我每次都会检查 _didReceiveMemoryWarning
变量,如果它变为 true,则关闭流。
...
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;
}
阅读可以在模拟器上进行,因为我在那里有足够的内存,但是在设备上,操作系统似乎在我收到通知之前杀死了应用程序(对于较小的文件,它也可以在设备上运行)。有谁知道这个问题的解决方案吗?
最佳答案
您可以尝试监视应用程序中的内存使用情况。此类添加通过 NSlog 显示应用程序正在使用的 MB。请记住,您不一定要寻找大量正在使用的内存,还要寻找内存的波动。
关于ios - 应用程序崩溃,未收到内存警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18206827/