2011-09-25 82 views
1

下面的代码显示了我如何削减我的精灵,但内存使用量不断增加。我该如何解决?精灵表问题

CGImageRef imgRef = [imgSprite CGImage]; 
[imgView setImage:[UIImage imageWithCGImage:CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height))]]; 
CGImageRelease(imgRef); 

该代码由NSTimer以0.1的间隔调用。

回答

2

由于您尚未发布imgSprite声明,因此我会假设其类遵循可可命名约定。

在:

CGImageRef imgRef = [imgSprite CGImage]; 

该方法(非NARC 方法)返回一个对象,你自己,因此你不应该释放。

在:

[imgView setImage:[UIImage imageWithCGImage:CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height))]]; 

的说法是表达:

CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height)) 

CGImageCreateWithImageInRect()(函数的名字如下创建规则)返回你自己的形象,因此你应该释放它,你不这样做。

在:

CGImageRelease(imgRef); 

你释放你自己的形象,所以你不应该释放。

您有两个问题:您(可能会超过)释放imgRef,并且您泄漏由CGImageCreateWithImageInRect()返回的图像。

你应该做的,而不是执行以下操作:

// you do not own imgRef, hence you shouldn’t release it 
CGImageRef imgRef = [imgSprite CGImage]; 

// use a variable for the return value of CGImageCreateWithImageInRect() 
// because you own the return value, hence you should release it later 
CGImageRef imgInRect = CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height)); 

[imgView setImage:[UIImage imageWithCGImage:imgInRect]]; 

CGImageRelease(imgInRect); 

你可能想读Memory Management Programming GuideMemory Management Programming Guide for Core Foundation

NARC =新,分配,保存,复制

Create Rule状态,如果你叫的名称包含创建或复制,然后你自己的返回值的函数,因此你应该释放当你不再需要它时。