gpt4 book ai didi

iphone - 释放 UIImage 会使应用程序崩溃

转载 作者:行者123 更新时间:2023-11-28 20:24:47 24 4
gpt4 key购买 nike

我的应用循环遍历图像路径数组并将所有这些图像合并为一个。代码如下。但是,当我在控制台中打印出带有 (gdb) 的图像时,应用程序崩溃了。如果我删除图像发布行,那么它可以正常工作,但这可能会导致内存泄漏。请查看此代码并解释为什么会发生这种情况以及可以改进的地方。谢谢。

UIGraphicsBeginImageContextWithOptions(CGSizeMake(width*len+padding*len+padding,
height+padding*2),
YES, 0.0);
do{

//draw image
path = (NSString*)[_imageData objectAtIndex:i];
UIImage * img = [[[UIImage alloc] initWithContentsOfFile:path]
cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
[img drawAtPoint: CGPointMake(width*i+padding*i+padding,padding) blendMode:kCGBlendModeNormal alpha:1];
[img release]; //APP CRASHES HERE BUT WORKS IF THIS LINE REMOVED
i++;
}while (i<len);
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(result, self,
@selector(image:didFinishSavingWithError:contextInfo:),
nil);

最佳答案

问题是您没有释放分配的图像。您正在释放自动发布的裁剪图像并泄漏分配的图像。

改变这个:

UIImage * img = [[[UIImage alloc] initWithContentsOfFile:path]
cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
[img drawAtPoint: CGPointMake(width*i+padding*i+padding,padding) blendMode:kCGBlendModeNormal alpha:1];
[img release];

到:

UIImage *original = [[UIImage alloc] initWithContentsOfFile:path];
UIImage *cropped = [original cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
[cropped drawAtPoint:CGPointMake(width * i + padding * i + padding, padding) blendMode:kCGBlendModeNormal alpha:1];
[original release];

我假设 cropCenterAndScaleImageToSize: 是某种返回自动释放的 UIImage 引用的类别方法。

关于iphone - 释放 UIImage 会使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14388951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com