我正在使用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]; }
如果它很大,为什么不将它写入文件,而不是将其保存在NSData对象中?
我正在使用
- (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]; }