精灵表问题

时间:2011-09-25 21:40:15

标签: objective-c cocoa-touch memory-management uiimage

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

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

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

1 个答案:

答案 0 :(得分:2)

由于您尚未发布imgSprite的声明,我将假设其类遵循Cocoa命名约定。

在:

CGImageRef imgRef = [imgSprite CGImage];

该方法(非NARC 1 方法)返回拥有的对象,因此不应释放它。

在:

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

参数是表达式:

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

CGImageCreateWithImageInRect()(名称遵循创建规则 2 的函数)会返回执行拥有的图像,因此应该释放它,你没有。

在:

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

1 NARC = new,alloc,retain,copy

2 Create Rule表示如果你调用名称中包含Create或Copy的函数,那么你就拥有了返回值,所以当你不需要它时你应该释放它。更长的时间。

相关问题