我正在使用NSURLConnection
类在我的iPhone应用程序中下载一个大文件,但它经常崩溃,因为它使用了太多的内存。我正在使用通常的NSURLConnection
用法,将收到的数据附加到NSMutableData
对象。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.fileData appendData:data];
}
然后在我下载完整个文件后,将其保存到本地临时文件中,并将其作为映射文件读取,如下所示:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// save the downloaded data into a temporary file
NSString *tempPath = NSTemporaryDirectory();
NSString *tempFile = [tempPath stringByAppendingPathComponent:@"temp.pdf"];
[self.fileData writeToFile:tempFile atomically:YES];
NSData *mappedData = [NSData dataWithContentsOfMappedFile:tempFile];
NSURL *baseURL = [NSURL URLWithString:@"http://mydomain.com"];
[webView loadData:mappedData MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:baseURL];
}
为了避免这些内存使用问题,我可以在这方面做些什么改进?
答案 0 :(得分:40)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response {
filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:save_name]; // filename is in .h file
[[NSFileManager defaultManager] createFileAtPath:filename contents:nil attributes:nil];
file =
[[NSFileHandle fileHandleForUpdatingAtPath:filename] retain];// file is in .h
//if (file) {
//
// [file seekToEndOfFile];
// }
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSD
ata *)data {
if (file) {
[file seekToEndOfFile];
} [file writeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
[file closeFile];
}
答案 1 :(得分:17)
如果它很大,为什么不将它写入文件,而不是将其保存在NSData对象中?
答案 2 :(得分:6)
我正在使用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:save_name];
NSFileHandle *file1 = [NSFileHandle fileHandleForUpdatingAtPath: filename];
[file1 writeData: data];
[file1 closeFile];
}