如何释放UIImageJPEGRepresentation或UIImagePNGRepresentation生成的数据?

时间:2011-02-22 02:24:37

标签: objective-c ios uiimagejpegrepresentation

我有这样的问题:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

NSData *data;

NSString *file1 = [[NSBundle mainBundle] pathForResource:
    [NSStringstringWithFormat:@"originimg_%d.jpg",i] ofType:nil]] ;

UIImage *image1 = [[UIImage alloc]initWithContentsOfFile:file1];
data = UIImageJPEGRepresentation(image, 0.7);
// do sth with data ...

[image1 release];
image1 = nil;
[pool drain];   
pool = nil;
if(data)
    NSLog(@"still exist");

我检查了数据是否仍然存在于内存中(我预计它会在我自动释放池消失后删除)但它仍然存在:(。您是否知道如何删除该数据?

2 个答案:

答案 0 :(得分:1)

非常感谢你,我测试过,这是真的。这是对我的问题的看法:我在设备中有132张图像(~300 kb / 1图像),现在我的目的是将每2张图像合并为1张大图像(水平方向并排)。这就是我的工作:

int index = 1;
for(int i = 1;i <= 132;i++)
{       
    if(i % 2 == 0 && i > 1)
    {                                   
        NSString *file = [NSString stringWithFormat:@"%@img_%d.jpg",path2,index];

        NSLog(@"index %d",index);
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        NSData *data;
        NSString *filename1 = [NSString stringWithFormat:@"originimg_%d.jpg",i];
        NSString *filename2 = [NSString stringWithFormat:@"originimg_%d.jpg",i + 1];
        NSString *file1 = [[NSBundle mainBundle] pathForResource:filename1 ofType:nil];
        NSString *file2 = [[NSBundle mainBundle] pathForResource:filename2 ofType:nil];

        UIImage *image1 = [[UIImage alloc]initWithContentsOfFile:file1];
        UIImage *image2 = [[UIImage alloc]initWithContentsOfFile:file2];

        UIImage *image = [self combineImages:image1 toImage:image2];                                
        data = UIImageJPEGRepresentation(image, 0.7);               
        [data writeToFile:file atomically:NO];

        [image1 release];
        image1 = nil;
        [image2 release];
        image2 = nil;                               

       [pool drain];    
       pool = nil;          
       [file release];
       file = nil;                              
       index++;
    }   
}           

和组合2张图片的功能

-(UIImage *)combineImages:(UIImage *)image1 toImage:(UIImage *)image2 
{   
    CGSize size;    
    size= CGSizeMake(768 * 2, 1024);
    UIGraphicsBeginImageContext(size);

    // Draw image1
    [image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];

    // Draw image2
    [image2 drawInRect:CGRectMake(image1.size.width, 0, image2.size.width, image2.size.height)];

    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();    
    return resultingImage ;
}
  • 这是我的方式,但是当我在乐器中运行时(Allocations)它需要303.4 mb :(。你能建议我一个更好的方法吗?

答案 1 :(得分:0)

我假设您在引用的代码之前省略了NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

您应该在发送image1之前释放[pool drain],因为您已经分配了data[pool drain]对象是自动释放的,这意味着它会在data中释放。但是,释放对象并不会将对象的所有指针神奇地设置为nil,因此NSLog(@"%@", data); 指向已解除分配的对象。只是为了踢,尝试以下而不是最后一行:

{{1}}

您的应用应该在此行崩溃,因为您无法向已解除分配的对象发送消息。

相关问题