代码改变世界

UIImage imageNamed引起的内存问题2

2012-10-12 16:02  三戒1993  阅读(165)  评论(0编辑  收藏  举报

UIImage imageNamed引起的内存问题

 126人阅读 评论(0) 收藏 举报

前段时间是遇到莫名其妙的崩最后于找出来是什么鬼原因 

1 [UIImage imageNamed:];

存了多的大致内存用尽最后崩最后解决问题的方法如下 
首先只存减小了大小的然后需要用到大从直接取不 
 
很明个方法不够好几天以后是无声无息的崩经过多次的排除了其他代 
的内存泄露等问题再看console里面一堆系内存警告然后退出了后台程知道用挂了 
 
所以很明+imageNamed个方法直太异了即使什么清空存什么的估也不管用 
 
并不是什么难题如果你干脆放弃存的苹果的例子代中有么一个函数足可使用函数的注的很清楚 

复制代码
- (UIImage *)tileForScale:(CGFloat)scale row:(int)row col:(int)col{
     // we use "imageWithContentsOfFile:" instead of "imageNamed:" here because we don't want UIImage to cache our tiles
    NSString *tileName = [NSString stringWithFormat:@"%@_%d_%d_%d", imageName, (int)(scale * 1000), col, row];
    NSString *path = [[NSBundle mainBundle] pathForResource:tileName ofType:@"png"]; 
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    return image;
}
复制代码

或者你非要比如我可以用一个NSMutableDictionary 

复制代码
 1 - (UIImage*)thumbnailImage:(NSString*)fileName
 2 { 
 3    UIImage *thumbnail = [thumbnailCache objectForKey:fileName
 4    if (nil == thumbnail)
 5    {
 6       NSString *thumbnailFile = [NSString stringWithFormat:@"%@/thumbnails/%@.jpg", [[NSBundle mainBundle] resourcePath], fileName];
 7       thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
 8       [thumbnailCache setObject:thumbnail forKey:fileName];
 9    }
10    return thumbnail;
11 }
复制代码

 
如果遇到内存低的警告只要

1 [thumbnailCache removeAllObjects];
OK 

 
所以如何在有大量片的情况下千万不要使用

1 [UIImage imageNamed];
异的方法了你可以试试上面的方法希望你有帮助