如何在没有外部库的情况下在UITableView中缓存图像?

时间:2014-06-15 13:18:20

标签: ios uitableview url uiimageview

Iam尝试在UITableview中不使用外部库来缓存图像。 但我没有得到任何结果。我的图片是从URL加载的。我有超过40张图片,有没有办法缓存而不是直接加载?

使用以下代码加载图片表单网址

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"cell";

    cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil)
    {
        cell = [[testingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:MyIdentifier]
        ;
    }


    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(concurrentQueue, ^{
        data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];

        dispatch_async(dispatch_get_main_queue(), ^{
            cell.img.image = [UIImage imageWithData:data];
        });
    });

    return cell;
}

2 个答案:

答案 0 :(得分:2)

您可以使用NSCache,NSCache的工作方式类似于NSMutableDictionary,具有线程安全的优势,还有一些自动删除策略  
根据您的要求,您可以创建它的单例实例:

@interface SharedCache : NSCache
+ (id)sharedInstance;

@end

@implementation SharedCache

- (void) emptyCache{
    [self removeAllObjects];
}


-(void) dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(id) init {
    self = [super init];
    if (self) {
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emptyCache) name:UIApplicationDidReceiveMemoryWarningNotification object:[UIApplication sharedApplication]];
    }
    return self;
}

+(id)sharedInstance
{
    static dispatch_once_t pred = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&pred, ^{
        _sharedObject = [[self alloc] init]; 
    });
    return _sharedObject;
}

@end

当然,您应该注意检查图像是否已使用指定的密钥进行缓存。

答案 1 :(得分:-1)

为什么不使用库?一个非常好用的是来自AFNetworking UIKit的UIImageView + AFNetworking,它以异步方式从URL加载图像并缓存图像。

示例代码:

[yourImageView setImageWithURL:youURL placeholderImage:[UIImage imageNamed:@"placeholder.png"]];