【发布时间】:2010-10-12 01:04:16
【问题描述】:
我正在使用 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];
}
我可以在这里改进什么来避免这些内存使用问题?
【问题讨论】:
-
我为此编写了一个库,我把它放在这里希望它对某些人有用,或者激励他们编写自己的解决方案。如果你没问题,当然可以。 github.com/thibaultCha/TCBlobDownload
标签: iphone memory-management nsurlconnection