imageNamed是邪恶的 – 如何使用该function

- (UIImage*)thumbnailImage:(NSString*)fileName { UIImage *thumbnail = [thumbnailCache objectForKey:fileName]; if (nil == thumbnail) { NSString *thumbnailFile = [NSString stringWithFormat:@"%@/thumbnails/%@.jpg", [[NSBundle mainBundle] resourcePath], fileName]; thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile]; [thumbnailCache setObject:thumbnail forKey:fileName]; } return thumbnail; } 

我从http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/得到了这段代码。 有人可以告诉我如何使用这个代码。 我只需要一点点帮助,如何使用这个来代替imageNamed。

 NSMutableDictionary *thumbnailCache=[[NSMutableDictionary alloc]init]; 

然后添加“缩略图”文件夹到你的资源文件夹,然后把你的PNG那里

 - (UIImage*)thumbnailImage:(NSString*)fileName { UIImage *thumbnail = [thumbnailCache objectForKey:fileName]; if (nil == thumbnail) { NSString *thumbnailFile = [NSString stringWithFormat:@"%@/thumbnails/%@.jpg", [[NSBundle mainBundle] resourcePath], fileName]; thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile]; [thumbnailCache setObject:thumbnail forKey:fileName]; } return thumbnail; } 

添加foo.png到资源文件夹//这里创buildUIImageView对象

 UIImageviewObject.image=[self thumbnailImage:@"foo.png"]; 

该代码使用NSMutableDictionary *thumbnailCache来cachingUIImage实例。 该代码假定在应用程序包中,有一个目录thumbnails缩小版本的图像。

该方法现在首先在thumbnailCache字典中查找给定图像的缩略图(它只是没有完整path的文件名,例如myimage.png )。 如果字典中不包含图像,图像将从thumbnails目录(使用imageWithContentsOfFile:而不是imageNamed: imageWithContentsOfFile:因为作者声称后者会导致麻烦)加载。 加载的图像然后存储在字典中,所以下一次应用程序要求缩略图时,它可以使用已经加载的实例。

要使此代码在您的应用中正常工作,您需要将thumbnails文件夹添加到您的项目中。 将其添加到项目中时,请确保select“为所有添加的文件夹创build文件夹引用”,而不是默认的“为所添加的文件夹创build组” 。 只有这样你才能在你的应用程序的主包中获得一个子目录,否则所有的文件都放在同一个顶层文件夹中。

但是, 重要的是提交人声称:

  • 避免[UIImage imageNamed:]
  • 相反,有一个NSMutableDictionary
  • 在字典中查找图像。
    • 如果find,使用。
    • 如果没有find,使用[UIImage imageWithContentsOfFile:]加载图像来手动加载图像并将其存储在字典中。

thumbnailCache是在头文件中声明的NSMutableDictionary,它应该以.m init方法或等价的方法初始化。

如果你有资源中的图像(使用jpg格式,否则在代码中将.jpg更改为.png),则该行应该像

  NSString *thumbnailFile = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], fileName]; 

而不是使用

 UIImage *thumbImage = [UIImage imageNamed:@"thumb.png"]; UIImage *thumbImage = [self thumbnailImage:@"thumb.png"];