0

我有这样的问题:

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");

我检查了数据是否仍然存在于内存中,(我预计在我耗尽自动释放池后它会被删除)但它仍然存在:(。你知道如何删除这些数据吗?

4

2 回答 2

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 ;
}
  • 这是我的方式,但是当我在仪器(分配)中运行时,它需要 303.4 mb :(。你能建议我一个更好的方式吗?
于 2011-02-22T06:54:02.723 回答
0

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

image1您应该在发送之前释放,[pool drain]因为您分配了它。该data对象是自动释放的,这意味着它会在[pool drain]. 但是,释放对象并不会神奇地将所有指向该对象的指针设置为 nil,而是指向data一个已释放的对象。只是为了好玩,请尝试以下而不是最后一行:

NSLog(@"%@", data);

您的应用程序应该在此行崩溃,因为您无法向已释放的对象发送消息。

于 2011-02-22T05:42:45.330 回答