iPhone SDK로 큰 파일을 다운로드하고 메모리 사용량 문제를 피하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/623735

문제

나는 사용하고있다 NSURLConnection iPhone 응용 프로그램에서 큰 파일을 다운로드하는 클래스이지만 너무 많은 메모리를 사용하고 있기 때문에 자주 충돌합니다. 나는 평소를하고있다 NSURLConnection 수신 된 데이터를 a로 추가하기 위해 사용법 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];
}

이러한 메모리 사용 문제를 피하기 위해 여기서 무엇을 개선 할 수 있습니까?

도움이 되었습니까?

해결책

그렇게 큰 경우 NSDATA 객체에 보관하지 않고 파일에 들어오는 것이 아닌 이유는 무엇입니까?

다른 팁

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

}

사용 중입니다

- (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];
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top