CGImageRelease导致崩溃

时间:2012-11-07 22:07:15

标签: objective-c ios uiimage

我正在使用AGImagePickerController从相册中挑选多张图片,然后将所选资源推送到viewController,在那里它尝试将每个资源转换为UIImage。 但是,我发现如果我选择了超过20张图像,我将开始获得内存不足警告并退出应用程序。这是我的转换代码

for(int i =0 ; i < [self.selectedPictures count] ; i++)
{
    NSLog(@"Object %d",i);
    ALAsset *asset = [self.selectedPictures objectAtIndex:i];
    ALAssetRepresentation *rep = [asset defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];
    UIImage *anImage = [UIImage imageWithCGImage:iref scale:[rep scale] orientation:(UIImageOrientation)[rep orientation]];
    float newHeight = anImage.size.height / (anImage.size.width / 1280);

    UIImage *resizedImage = [anImage resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:CGSizeMake(newHeight, 1280.f) interpolationQuality:kCGInterpolationHigh];

    UIImage *resizedThumbnailImage = [anImage resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:CGSizeMake(290.0f, 300.f) interpolationQuality:kCGInterpolationHigh];

    // JPEG to decrease file size and enable faster uploads & downloads
    NSData *imageData = UIImageJPEGRepresentation(resizedImage, 0.6f);
    //NSData *thumbnailImageData = UIImagePNGRepresentation(thumbnailImage);
    NSData *thumbnailImageData = UIImageJPEGRepresentation(resizedThumbnailImage, 0.6f);


    PFFile *photoFile = [PFFile fileWithData:imageData];
    PFFile *thumbnailFile = [PFFile fileWithData:thumbnailImageData];

    [photoFile saveinbackground];
    [thumbnailFile saveinbackground];
}

所以我发现我应该添加CGImageRelease(iref);在anImage释放iref之后,内存警告消失了。但是,在最后一个资产转换为UIImage后,我的应用程序将崩溃。到目前为止,我无法找出崩溃的原因。

2 个答案:

答案 0 :(得分:3)

除非您使用CGImageRelease(iref);,否则您不应该CGImageCreateCGImageCreateCopyCGImageRetain。这就是崩溃的原因。

答案 1 :(得分:-1)

我找到了解决这个问题的方法。 使用@autoreleasepool