- (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;
}
I got this code from http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/ . Can someone tell me how to use this code. I need just a little help how to use this in place of imageNamed.
The code uses a
NSMutableDictionary *thumbnailCache
to cache UIImage instances. The code assumes that in the app bundle, there's a directorythumbnails
with scaled down versions of their images.The method now first looks in the
thumbnailCache
dictionary whether the thumbnail for the given image (which is only a filename without full path, e. g.myimage.png
). If the dictionary did not contain an image already, the image is loaded from thethumbnails
directory (usingimageWithContentsOfFile:
instead ofimageNamed:
, since the authors claim the later causes trouble). The loaded image is then stored in the dictionary so the next time the app asks for the thumbnail, it can use the already loaded instance.For this code to work correctly in your app, you need to add a
thumbnails
folder to your project. When you add it to your project, be sure to select "Create folder references for any added folders" instead of the default "Create groups for any added folders". Only then you will get a subdirectory in your app's main bundle, otherwise all files are put into the same top-level folder.But the whole point is that the author claims:
[UIImage imageNamed:]
.NSMutableDictionary
.[UIImage imageWithContentsOfFile:]
to manually load the image and store it in the dictionary.thumbnailCache
is NSMutableDictionary declared in header file and it should be initialized in .minit
method or equivalent method.If u have the images in the resources (with jpg format, else change the .jpg to .png in the code), then the line should be like
Instead of using
then add "thumbnails" folder to ur resource folder then put ur png there
example
add foo.png to resource folder //here create UIImageView object then