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

查看:91
本文介绍了如何使用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天全站免登陆