Iphone iOS中UIImage的内存泄漏

Iphone iOS中UIImage的内存泄漏,iphone,ipad,Iphone,Ipad,UIImage对象可能存在内存泄漏问题。代码如下。请帮忙 UIImage *image = nil; if (x == 0) { image = [UIImage imageWithCGImage:cg1]; } else { image = [UIImage imageWithCGImage:cg2]; } UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; [image release]

UIImage对象可能存在内存泄漏问题。代码如下。请帮忙

UIImage *image = nil; if (x == 0) { image = [UIImage imageWithCGImage:cg1]; } else { image = [UIImage imageWithCGImage:cg2]; } UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; [image release]; UIImage*image=nil; 如果(x==0){ image=[UIImage imageWithCGImage:cg1]; }否则{ image=[UIImage imageWithCGImage:cg2]; } UIImageView*imageView=[[UIImageView alloc]initWithImage:image]; [图片发布]; 我试图在if-else块之后释放UIImage对象,但Xcode警告说“此时调用方不拥有的对象的引用计数减少不正确”

如果我删除[image release],它将显示“在线分配的对象的潜在泄漏…”

如何解决这个问题


谢谢。

问题在于
[UIImage new]
[[UIImage alloc]init]
相同,因此您已经保留了一个实例。然后通过调用
[UIImage imageWithCGImage:
,将指向实例的指针扔掉,这将返回一个不需要保留的自动释放实例


解决方案是从代码中抛出
[UIImage new]
,以及最后的
[image release]

问题是
[UIImage new]
[[UIImage alloc]init]
相同,因此您已经有了一个保留的实例。然后通过调用
[UIImage imageWithCGImage:
,将指向实例的指针扔掉,这将返回一个不需要保留的自动释放实例


解决方案是从代码中抛出
[UIImage new]
,以及在最后抛出
[image release]

您正在使用
new
方法分配
UIImage
对象的新实例,并将其分配给
image
变量。然后使用
imageWithCGImage:
方法将不同的实例分配给变量,从而立即泄漏该实例

您不需要执行
UIImage*image=[UIImage new]在开头。您可以简单地声明变量,而无需为其分配任何实例。好的做法是最初将
nil
分配给它


执行此操作后,不需要稍后释放图像对象,因为
imageWithCGImage
返回自动释放的对象

您正在使用
new
方法分配
UIImage
对象的新实例,并将其分配给
image
变量。然后使用
imageWithCGImage:
方法将不同的实例分配给变量,从而立即泄漏该实例

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];
您不需要执行
UIImage*image=[UIImage new]在开头。您可以简单地声明变量,而无需为其分配任何实例。好的做法是最初将
nil
分配给它

执行此操作后,不需要稍后释放图像对象,因为
imageWithCGImage
返回自动释放的对象

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];
您拥有对象
imageView
的所有权,而不是
image
。所以你应该发布
imageView
,而不是
image
。看看


您拥有对象
imageView
的所有权,而不是
image
。所以你应该发布
imageView
,而不是
image
。看看

是的,你也需要扔掉[image release],因为该图像已经自动删除。谢谢,但在我删除[image release]后,它显示“在线分配的对象可能泄漏…”。请帮助。是的,你也需要扔掉[image release],因为该图像已经自动删除。谢谢,但在我删除[image release]后,它显示“在线分配的对象可能泄漏…”。请帮忙,我试过你的建议了。警告仍然显示-在线分配的对象可能泄漏…如何调查?我试过使用仪器,但我真的不知道如何使用它来检查泄漏。当你使用构建和分析时,你会得到一个显示泄漏的蓝色图标。单击它以显示您的建议。警告仍然显示-在线分配的对象可能泄漏…如何调查?我试过使用仪器,但我真的不知道如何使用它来检查泄漏。当你使用构建和分析时,你会得到一个显示泄漏的蓝色图标。单击它以显示您的建议。警告仍然显示-在线分配的对象可能泄漏。。。有什么解决办法吗?试过你的建议。警告仍然显示-在线分配的对象可能泄漏。。。有什么解决办法吗?