需要在app的Documents文件夹中为图像加载延迟表图像

问题描述 投票:2回答:1

我将我的图像放入iPhone应用程序的文档目录中。

我把它们加载到表格中。但我希望它们作为懒惰的表格图像加载。

我搜索过网络,但找到了从服务器加载图片的链接。如何从我的文档目录中加载它们?

我试过这个链接,但它对我不起作用:

Lazy load images for UITableViewCells from NSDocumentDirectory?

iphone cocoa-touch uitableview ios4 lazy-loading
1个回答
1
投票

可以轻松修改从服务器下载图像的工作解决方案,以从NSDocumentsDirectory加载。这是一个简单的实现,您可以将其创建为独立类或集成到现有类中。我没有包含100%的代码,只是放入足以显示加载图像。 imageLoader.h需要定义一个协议,包括imageLoader:didLoadImage:forKey:_delegate_images的iVars /属性。

// 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.