0

我有很多内存泄漏......例如,我有一个 UIImageView,每次更新时都会翻转图像(动画大约是 30fps,所以这个图像会更新并翻转很多)

image2 = [[UIImage alloc] initWithCGImage:image2.CGImage scale:image2.scale orientation:UIImageOrientationUpMirrored];

它有大量的内存泄漏,所以我在翻转一次后释放了它:

image2 = [[UIImage alloc] initWithCGImage:image2.CGImage scale:image2.scale orientation:UIImageOrientationUpMirrored];
[image2 release];

但不是问题是如果我再次尝试运行该代码,应用程序会冻结(我猜你不能释放一些东西然后再次使用它?(对整个内存分配和释放东西有点新......

我该怎么办?如果图像已发布,我是否在尝试翻转图像之前重新定义图像?谢谢!

4

3 回答 3

2

可能最简单的方法是使 image2 成为保留属性,然后分配给self.image2而不是 plain image2。这将导致在分配新值时释放旧图像。但是你需要在autorelease你的调用中添加一个调用[UIImage alloc] init...来释放由alloc.

于 2012-03-11T20:49:01.987 回答
2

通过重用相同的变量名,您会造成不必要的混乱。添加一个临时变量。

UIImage* image; // assuming you set this up earlier, and that it's retained
UIImage* flippedImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:UIImageOrientationUpMirrored];
// Now we're done with the old image. Release it, so it doesn't leak.
[image release];
// And set the variable "image" to be the new, flipped image:
image = flippedImage;
于 2012-03-11T20:50:42.677 回答
1

您需要将图像视图的image属性设置为生成的图像,然后释放分配的图像。例如:

image2 = [[UIImage alloc] initWithCGImage:image2.CGImage scale:image2.scale orientation:UIImageOrientationUpMirrored];
self.someImageView.image = image2;
[image2 release];

或者,您可以只自动释放返回的图像。像这样:

image2 = [[[UIImage alloc] initWithCGImage:image2.CGImage scale:image2.scale orientation:UIImageOrientationUpMirrored] autorelease];
self.someImageView.image = image2;

编辑:在你澄清你的要求之后,这里有一个更好的方法来垂直翻转你的图像。

//lets suppose your image is already set on the image view
imageView.transform = CGAffineTransformIdentity;
imageView.transform = CGAffineTransformMakeScale(1.0, -1.0);

那么当你想把它改回正常时:

imageView.transform = CGAffineTransformIdentity;
于 2012-03-11T20:47:11.663 回答