简体   繁体   English

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

[英]How to cache images in UITableView without external Libraries?

Iam trying to cache images without using external libraries in UITableview. 我试图在不使用UITableview中的外部库的情况下缓存图像。 But i didnt get any results for that. 但是我没有得到任何结果。 My images are loading from URL .i have more than 40 images and is there any way to cache rather than loading directly ?? 我的图片是从URL加载的。我有40多个图片,有什么方法可以缓存而不是直接加载?

am using following code for loading image form URL 正在使用以下代码加载图片表单网址

- (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;
}

You can use NSCache , NSCache works like an NSMutableDictionary with the advantage that is thread safe, with also some auto removal policies 您可以使用NSCache ,NSCache就像NSMutableDictionary一样,具有线程安全的优点,并且还具有一些自动删除策略
Depending on your requirements you can create a singleton instance of it: 根据您的要求,您可以创建一个单例实例:

@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

Of course you should take care about check whether or not the image is already cached with a specified key. 当然,您应该注意检查图像是否已经使用指定的密钥进行了缓存。

Why wouldn't you use libraries? 为什么不使用库? A very good one to use is UIImageView+AFNetworking from AFNetworking UIKit which loads an Image from a URL asynchronously and also caches your images. AFNetworking UIKit中的UIImageView + AFNetworking是很好用的一种,它可以异步地从URL加载图像,也可以缓存图像。

example code: 示例代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM