2013-03-15 44 views
2

我使用以下代碼從服務器下載許多文件。 其中一些文件是視頻文件(> 60Mo)。下載很多大文件時iOS內存警告

該函數在循環中調用。它適用於小文件...

當我下載太多(這取決於)大文件,我有內存警告,然後應用程序崩潰。

注:該項目是ARC

- (bool) copyWebFile:(NSString *)url toFile:(NSString *)toFile ; 
{ 
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]] ; 
    if (data) 
    { 
    NSError *error ; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:toFile]) 
    { 
     NSLog(@"Existant %@", toFile) ; 
     [[NSFileManager defaultManager] removeItemAtPath:toFile error:nil] ; 
    } 
    if ([data writeToFile:toFile options:NSDataWritingAtomic error:&error]==NO) 
    { 
     NSLog(@"@Error creating file-%@ \n", toFile) ; 
     NSLog(@"@Error description-%@ \n", [error localizedDescription]) ; 
     NSLog(@"@Error suggestion-%@ \n", [error localizedRecoverySuggestion]) ; 
     NSLog(@"Error reason-%@", [error localizedFailureReason]) ; 
    } 
    else 
    { 
     return(true) ; 
    } 
    } 
    return(false) ; 
} 

在我的應用程序委託,我添加以下代碼:沒有區別。

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application 
{ 
    [[NSURLCache sharedURLCache] removeAllCachedResponses] ; 
} 

回答

0

使用@autoreleasepool和嘗試這樣的..

- (bool) copyWebFile:(NSString *)url toFile:(NSString *)toFile ; 
    { 
     @autoreleasepool 
     { 
      NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]] ; 
      if (data) 
      { 
       NSError *error ; 
       if ([[NSFileManager defaultManager] fileExistsAtPath:toFile]) 
       { 
        NSLog(@"Existant %@", toFile) ; 
        [[NSFileManager defaultManager] removeItemAtPath:toFile error:nil] ; 
       } 
       if ([data writeToFile:toFile options:NSDataWritingAtomic error:&error]==NO) 
       { 
        NSLog(@"@Error creating file-%@ \n", toFile) ; 
        NSLog(@"@Error description-%@ \n", [error localizedDescription]) ; 
        NSLog(@"@Error suggestion-%@ \n", [error localizedRecoverySuggestion]) ; 
        NSLog(@"Error reason-%@", [error localizedFailureReason]) ; 
       } 
       else 
       { 
        return(true) ; 
       } 
      } 
      return(false) ; 
     } 
    } 
+1

'@ autoreleasepool'只會幫助的時候有許多小或中等大文件,而不是當它們很大時。 1GB仍將被加載到內存中,該應用程序將崩潰。 – coverback 2013-03-15 10:14:19