问题描述
|
我有UIImage对象的潜在内存泄漏问题。代码如下。请帮忙。
UIImage * image = nil;
如果(x == 0){
图片= [UIImage imageWithCGImage:cg1];
}其他{
图片= [UIImage imageWithCGImage:cg2];
}
UIImageView * imageView = [[UIImageView alloc] initWithImage:image];
[图片发布];
我尝试在if-else块之后释放UIImage对象,但是Xcode警告\“调用者此时不拥有的对象的引用计数错误减少”,
如果删除[image release],它会显示\“在行...上分配的对象可能泄漏”。
如何解决问题?
谢谢。
解决方法
UIImage *image = nil;
if (x == 0) {
image = [UIImage imageWithCGImage:cg1];
} else {
image = [UIImage imageWithCGImage:cg2];
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// Some code
[imageView release];
您拥有对象“ 1”而不是“ 2”的所有权。所以你应该释放imageView
而不是release2 release。在Apple的“内存管理”指南中查看对象所有权
,问题在于[UIImage new]
与[[UIImage alloc] init]
相同,因此您已经有一个保留实例。然后,您通过调用[UIImage imageWithCGImage:]
将指针指向该实例,该指针将返回不需要保留的自动释放实例!
解决方案是将代码中的“ 5”以及最后的“ 9”扔掉。
,您正在使用new
方法分配UIImage
对象的新实例,并将其分配给image
变量。然后,您将使用imageWithCGImage:
方法为变量分配其他实例,从而立即泄漏该实例。
开始时不需要做UIImage *image = [UIImage new];
。您可以简单地声明变量,而无需为其分配任何实例。优良作法是最初分配ѭ15。
执行此操作时,以后将不需要释放图像对象,因为ѭ16返回一个自动释放的对象。