iphone - 如何使用iPhone SDK下载大文件并避免内存使用问题?

标签 iphone memory-management nsurlconnection

我正在使用 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];
}

我可以在此处进行哪些改进来避免这些内存使用问题?

最佳答案

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

}

关于iphone - 如何使用iPhone SDK下载大文件并避免内存使用问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/623735/

相关文章:

iphone - 将 UITextField 放置在 View 的中心

ios - 如何通过 UICollectionView 捕捉手势?

iphone - 在特定时间执行某项功能

c - Linux 内核的 free_list 如何初始化为指向空闲页面?

ios - 子类化 NSURLConnection 给出错误 : unrecognized selector sent to instance

iphone - 后台异步任务

iphone - 根据不在设备设置上的应用程序设置,在 UIDatepicker 中以 12 和 24 小时格式显示时间

iphone - 如何在获取请求时调试核心数据崩溃

c++ - 为什么保留的虚拟内存会增长而当前正在使用的虚拟内存不会增长?

cocoa - 为什么我收到 1 个 302 响应时会得到两个重定向响应?