How to download a large file with the iPhone SDK and avoid memory usage issues?

前端 未结 3 1871
半阙折子戏
半阙折子戏 2020-12-04 11:26

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

相关标签:
3条回答
  • 2020-12-04 12:04

    i'm using

    - (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];
    }
    
    0 讨论(0)
  • 2020-12-04 12:23

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

    0 讨论(0)
  • 2020-12-04 12:24
    - (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]; 
    
    }
    
    0 讨论(0)
提交回复
热议问题