iphone - 需要对应用程序的文档文件夹中的图像进行延迟表图像加载

标签 iphone cocoa-touch uitableview ios4 lazy-loading

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

我将它们加载到表中。但我希望它们作为惰性表格图像加载。

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

我尝试了此链接,但它对我不起作用:

Lazy load images for UITableViewCells from NSDocumentDirectory?

最佳答案

从服务器下载图像的工作解决方案可以轻松修改为从 NSDocumentsDirectory 加载。这是一个简单的实现,您可以将其创建为独立类或集成到现有类中。我没有包含 100% 的代码,只是添加了足够的代码来显示加载图像。 imageLoader.h需要定义一个协议(protocol),包括 imageLoader:didLoadImage:forKey:以及 _delegate 的 iVars/properties和_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;
}

关于iphone - 需要对应用程序的文档文件夹中的图像进行延迟表图像加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5606534/

相关文章:

iphone - iOS 中的原生 JSON 支持?

ios - 不推荐使用旋转方法,相当于 'didRotateFromInterfaceOrientation' ?

objective-c - UITextField/UITextView : I need to be able to detect user "return" key, 并且我需要能够执行多行...什么可以同时执行?

cocoa-touch - 更改 Cocoa 单元测试的系统日期

iPhone:如何修复基于更改设备日期的作弊行为?有服务器可以获取时间吗?

iphone - 如何通过 iPhone 应用程序将图像附加到消息中?

ios - 当单元格文本标签太长时,UITableViewCell的detailTextLabel文本消失

uitableview - 删除分组 UITableView 中的分隔符

ios - TableView :numberOfRowsInSection error when searching

ios - 拆除 UITableViewDataSource