Need lazy table image load for images in app's Documents folder
I have my images into my iPhone applicati开发者_高级运维on's documents directory.
I load them into table. But I want them to load as lazy table images.
I have searched the web, but found the links where images are loaded from server. How can I load them from my documents directory?
I tried this link but it didn't work for me:
Lazy load images for UITableViewCells from NSDocumentDirectory?
A working solution that downloads images from a server can easily be modified to load from the NSDocumentsDirectory. Here's a simple implementation that you can create as a stand-alone class or integrate into an existing class. I did not include 100% of the code, just put in enough to show loading the images. imageLoader.h
needs to define a protocol including imageLoader:didLoadImage:forKey:
and the iVars/properties for _delegate
and _images
.
// imageLoader.m
// assumes that that images are cached in memory in an NSDictionary
- (UIImage *)imageForKey:(NSString *)key
{
// check if we already have the image in memory
UImage *image = [_images objectForKey:key];
// if we don't have an image:
// 1) start a background task to load an image from available sources
// 2) return a default image to display while loading
if (!image) {
// this is the simplest example of background execution
// if you need more control use NSOperationQueue or Grand Central Dispatch
[self performSelectorInBackground:@selector(loadImageForKey) withObject:key];
image = [self defaultImage];
}
return image;
}
// attempts to load an image from available sources and notifies the delegate when done
- (void)loadImageForKey:(NSString *)key
{
NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
// attempt to load the image from a file
UIImage *image = [UIImage imageWithContentsOfFile:[self imagePathForKey]];
// if no image, attempt to load the image from an URL here if desired
// if no image, return default or notFound image
if (!image) {
image = [self notFoundImage];
}
if ([_delegate respondsTo:@selector(imageLoader:didLoadImage:ForKey:)]) {
// this message will be sent on the same thread as loadImageForKey
// you can either modify this to send the message on the main thread
// or ensure the delegate does any desired UI changes on the main thread
[_delegate imageLoader:self didLoadImage:image forKey:key];
}
[pool release];
}
// returns a path to the image in NSDocumentDirectory
- (NSString)imagePathForKey:(NSString *)key
{
NSString *path;
// your implementation here
return path;
}
精彩评论