如何使用 iPhone SDK 下载大文件并避免内存使用问题? [英] How to download a large file with the iPhone SDK and avoid memory usage issues?

查看:35
本文介绍了如何使用 iPhone SDK 下载大文件并避免内存使用问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 NSURLConnection 类在我的 iPhone 应用程序中下载一个大文件,但它经常崩溃,因为它使用了太多内存.我正在执行通常的 NSURLConnection 用法,将接收到的数据附加到 NSMutableData 对象.

I'm using the NSURLConnection class to download a large file in my iPhone application, but it crashes every so often because it's using too much memory. I'm doing the usual NSURLConnection usage, to append the received data to a NSMutableData object.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.fileData appendData:data];
}

然后在我下载完整个文件后,将其保存到本地临时文件中,并将其作为映射文件读取,如下所示:

Then after I finish downloading the whole file, I save it to a local temporary file, and read it as a mapped file like this:

- (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];
}

我可以在这里改进什么来避免这些内存使用问题?

What can I improve here to avoid these memory usage problems?

推荐答案

如果它那么大,为什么不把它写入文件,而是将它保存在 NSData 对象中?

If it's that large, why not write it to the file as it comes in, rather than keeping it in an NSData object?

这篇关于如何使用 iPhone SDK 下载大文件并避免内存使用问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆