将图像存储在缓存中目标c

时间:2016-12-07 12:42:17

标签: ios objective-c cocoa-touch lazy-loading

在UITableviewcell中我有很多图像视图,它将从url加载图像

我想将图像存储在缓存中,这样当我再次滚动时,它不应该从url加载

我的代码是

UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                [indicator startAnimating];
                [indicator setCenter:cell.image_VW.center];
                [cell.contentView addSubview:indicator];
NSString *url_STR = [NSString stringWithFormat:@"%@news/%@",IMAGE_URL,[tmp_NEWS valueForKey:@"image"]];              
NSString *url_STR = [NSString stringWithFormat:@"%@news/%@",IMAGE_URL,[tmp_NEWS valueForKey:@"image"]];                  
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   //retrive image on global queue
   UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url_STR]]];
   dispatch_async(dispatch_get_main_queue(), ^{
                     [indicator removeFromSuperview];
   NEWS_BIG_CELL * cell = (NEWS_BIG_CELL *)[self.tbl_CONTENTS cellForRowAtIndexPath:indexPath];
   //assign cell image on main thread
   //cell.image_VW.contentMode = UIViewContentModeScaleAspectFit;
            cell.image_VW.image = img;
   });
});

3 个答案:

答案 0 :(得分:0)

你应该使用NSCache,你可以用密钥保存你的图像,如果它们存在于缓存中(按键),你可以得到它们,请看这个快速的例子:

http://www.splinter.com.au/2015/09/24/swift-image-cache/

或使用:

https://github.com/rs/SDWebImage

答案 1 :(得分:0)

对于简单解决方案,SDWebImage用于缓存图片gitHub链接

在您的UITableviewcell cellForRowAtIndexPath方法

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    [cell.image_VW sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                 placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    return cell;
}

答案 2 :(得分:0)

首先,您需要检查 dataWithContentsOfURL 中的数据是否为零,然后检查是否为真:

您可以将图像保存为 NSUserdefaults 中的NSData,并将其URL作为该首选项的键( setObject:(NSData)forKey :( URL as NSString)),所以,下次你可以检查缓存中是否存在URL的任何数据,以便立即显示它而不从互联网再次获取它( objectForKey:(URL as NSString))。