我目前面临以下问题:将图像添加到一个数组的内存问题
我的应用程序动态生成图像(320×480像素),并将它们添加到NSMutableArray里。我需要这些数组内的图像,以便用户来回浏览它们。我只需要保留最新的5张图片。所以我写了类似下面的方法:
- (void)addImageToArray:(UIImage*)theImage {
if ([myMutableArray count] < 5) {
[myMutableArray addObject:theImage];
}
else {
[myMutableArray removeObjectAtIndex:0];
[myMutableArray addObject:theImage];
}
}
这种方法基本上做什么它应该做的。但是,在我看到的工具中,内存使用率永久增加。在某个时候,即使我没有任何内存泄漏,应用程序最终崩溃。 我看到它的方式,XCode会从我的数组中删除图像,但不会释放它。有没有一种方法可以确保,我想从阵列中移除的对象也将被释放?也许我的方法是完全错误的,我需要找到一种不同的方式。
任何帮助表示赞赏。在此先感谢
[编辑:]
按照要求,我将我的代码,它创建的图像部分:
-(UIImage*)getGL {
unsigned char buffer[320*480*4];
glReadPixels(0,0,320,480,GL_RGBA,GL_UNSIGNED_BYTE,&buffer);
CGDataProviderRef ref = CGDataProviderCreateWithData(NULL, &buffer, 320*480*4, NULL);
CGImageRef iref = CGImageCreate(320,480,8,32,320*4,CGColorSpaceCreateDeviceRGB(),kCGBitmapByteOrderDefault,ref,NULL,true,kCGRenderingIntentDefault);
size_t width = CGImageGetWidth(iref);
size_t height = CGImageGetHeight(iref);
size_t length = width*height*4;
uint32_t *pixels = (uint32_t *)malloc(length);
CGContextRef _context = CGBitmapContextCreate(pixels, width, height, 8, width*4, CGImageGetColorSpace(iref), kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextTranslateCTM(_context, 0.0, height);
CGContextScaleCTM(_context, 1.0, -1.0);
CGContextDrawImage(_context, CGRectMake(0.0, 0.0, width, height), iref);
CGImageRef outputRef = CGBitmapContextCreateImage(_context);
UIImage *outputImage = [UIImage imageWithCGImage:outputRef];
CGDataProviderRelease(ref);
CGImageRelease(iref);
CGImageRelease(outputRef);
CGContextRelease(_context);
return outputImage;
}
所以,现在我可以做这样的事情:
[self addImageToArray:[self getGL]];
希望,这有助于。再次感谢。
你*禁用* NSZombie? – kennytm 2010-03-27 21:25:46
问题可能在于初始化图像的方式。在你的问题中也包括你的代码的一部分。 – RunLoop 2010-03-27 21:30:04
我不记得首先启用它。它是否默认打开? – Friendlydeveloper 2010-03-27 21:30:39