2014-09-23 59 views
0

我將UIImage保存到Library目錄,但這需要更多的內存來保存圖像我編寫此代碼以保存圖像。UIImage保存到文檔目錄的內存使用率低

int i; 
for(i = 0; i<[_selectedAssetArray count]; i++) 
{ 
    NSError *error; 
    NSString *documentsDirectory = [NSHomeDirectory() 
            stringByAppendingPathComponent:@"Library/VideoMaker"]; 
    if (![[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory]) 
     [[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:NO attributes:nil error:&error]; 
     UIImage *image=[_selectedAssetArray objectAtIndex:i]; 

     NSData *imageData = UIImageJPEGRepresentation(image, 1.0f); 
     [imageData writeToFile:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"Di%d.%@",i, @"png"]] atomically:YES]; 
}i++; 

在這段代碼_selectedAssetArray是我UIImage Array包含超過50個OR100圖像。 當我保存圖像的內存從20 MB增加到200或更多。所以我的應用程序終止,由於內存的壓力...

+1

您可以檢查此鏈接... http://stackoverflow.com/questions/25324990/how-to-save-nsmutable-array-image-into-plist-or-document-folder-multiple-images – 2014-09-27 13:06:45

回答

0

這可能是值得一試,把它放在一個低隊列,或甚至試圖通過BACKGROUND

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0ul), ^{ 

    // Your code here 
     [self saveData:1] 
}); 

編輯替換LOW:比方說,您的所有照片都保存在photoArray,這是一個NSMutableArray。

請注意,這需要一些縮進,我已經在SO上從頭開始鍵入。此外,這是非常非常難看,所以如果它的工作原理,你需要一點調整它(例如,至少使用一個開關的進行,也許分成,使這個更具可讀性的方法)

- (void)saveData:(int)proceed 
{ 
    if (proceed == 1){ 
     if([photoArray count] >= 10){ 
      (for int i = 0 ; i < 10; i++){ 

      // I'm making up the code but you'll know what i mean 
      // I'm saving the last photo (or the first one, it doesn't matter) 
      // of the array of pictures 

      [self savePhoto:[photoArray lastObject]]; 

      // now your photo has ben saved, 
     // we can remove if from the array so the loop doesn't do it twice 

      [photoArray removeObject:[photoArray lastObject]]; 
     } 
     // Here you check if you have to start over, or just do the last photos. 
     if ([photoArray count] >= 10){ 
      [self saveData:1]; 
      } 
     if ([photoArray count] < 10 && [photoArray count] >0){ 
      [self saveData:2]; 
      } 
     if ([photoArray count] == 10){ 
      break; 
      } 
     } 
    } 
    if (proceed == 2) 

     if([photoArray count] < 10 && [photoArray count] > 0){ 
      (for int i = 0 ; i < [photoArray count]; i++){ 
      // I'm making up the code but you'll know what i mean 
      // I'm saving the last photo (or the first one, it doesn't matter) 
      // of the array of pictures 

      [self savePhoto:[photoArray lastObject]]; 

      // now your photo has ben saved, 
     // we can remove if from the array so the loop doesn't do it twice 

      [photoArray removeObject:[photoArray lastObject]]; 
      } 
+0

它不工作......任何其他的想法..?請幫助我 – 2014-09-23 10:01:29

+0

好的,那麼你應該做的是(在仍然使用背景隊列的時候)使用一次做10張圖片的方法,並且當第10張圖片被處理時再次調用自己。這可能有助於記憶的高峯期。 – 2014-09-23 11:06:41

+0

我想將圖像保存到庫以備後用。我正在創建VideoMaker應用程序。 – 2014-09-23 11:10:43