UIButton与表视图中的精灵表背景图像导致内存警告?

时间:2013-09-24 03:59:42

标签: iphone ios objective-c ipad

我的文档目录中有一个精灵表。精灵表由256个图标组成。

我有一个表视图,其中每行我创建3个按钮,其中包含来自精灵表的切片部分的背景图像。

以下是从精灵中提取切片图标的代码。使用已知的坐标

    -(UIImage *)getSlicedImageForDictionary:(NSDictionary *)spriteInfoDictionary spriteImageRef:(UIImage *)spriteImageReference{

    NSString *frameString = [spriteInfoDictionary objectForKey:@"frame"];
    NSString *frameStringWithOnlyCommas = [[[frameString stringByReplacingOccurrencesOfString:@"\"" withString:@""] stringByReplacingOccurrencesOfString:@"{" withString:@""] stringByReplacingOccurrencesOfString:@"}" withString:@""];

    NSArray *frameValues = [frameStringWithOnlyCommas componentsSeparatedByString:@","];

    CGImageRef cgIcon = CGImageCreateWithImageInRect(spriteImageReference.CGImage, CGRectMake([[frameValues objectAtIndex:0] floatValue],     [[frameValues objectAtIndex:1] floatValue], [[frameValues objectAtIndex:2] floatValue], [[frameValues objectAtIndex:3] floatValue]));
    UIImage *icon = [UIImage imageWithCGImage:cgIcon];
    frameString = nil;
    frameStringWithOnlyCommas = nil;
    frameValues = nil;
    CGImageRelease(cgIcon);
    return icon;
}

我在for循环中调用上面的方法,如下所示,

for (int i = 0; i < [iconInfoArray count]; i ++) {   
   NSDictionary *currentBook = [spriteInfoDictionary objectForKey:[iconInfoArray objectAtIndex:i]];
   articleMetaData.articleImage = [self getSlicedImageForDictionary:currentBook spriteImageRef:self.spriteImageSource];
   [spriteIconsArray addObject:articleMetaData];
}

问题是, 当我从spriteIconsArray中设置表视图中的按钮时,我收到“已接收内存警告”问题并且应用程序崩溃。

[btn setBackgroundImage:[spriteIconsArray objectAtIndex:i] forState:UIControlStateNormal];

但是当我将图像引用写入文档目录时,我没有得到任何内存警告,应用程序运行顺利。

NSData *data = UIImagePNGRepresentation([spriteIconsArray objectAtIndex:i]);
NSString *pathOfTempImage = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"tempIcon.png"];
[data writeToFile:pathOfTempImage atomically:YES];
[btn setBackgroundImage:pathOfTempImage forState:UIControlStateNormal];

我很困惑为什么会这样。我不想将图像写入文档并再次阅读,这可能会为大量数据创建一些延迟。

请在此建议我。

由于

0 个答案:

没有答案