UIImage保存到文件目录,内存使用率低

时间:2014-09-23 07:24:59

标签: ios objective-c uiimage nsdata

我将UIImage保存到Library目录,但这需要更多内存来保存图像我编写此代码来保存图像。

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数组,其中包含超过50或100个图像。 当我保存图像时,内存从20 MB增加到200或更多。所以我的应用由于内存压力而终止...

1 个答案:

答案 0 :(得分:0)

这可能值得一试,将其置于LOW队列中,甚至尝试将LOW替换为BACKGROUND

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

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

编辑:假设您的所有照片都保存在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]];
            }