What is the proper way to use NSCache with dispatch_async in a reusable table cell?

前端 未结 2 1689
长发绾君心
长发绾君心 2020-12-13 16:13

I have been looking for a clear cut way to do this and have not found anywhere that will give an example and explain it very well. I hope you can help me out.

Here i

2条回答
  •  既然无缘
    2020-12-13 16:53

    Might be you did some wrong you setting same Key for each image of NSCache

    [cache setValue:[UIImage imageWithData:imageData] forKey:@"image"];
    

    Use this Instead of above set ForKey as a Imagepath item.image and use setObject instead of setVlaue:-

    [self.imageCache setObject:image forKey:item.image];
    

    try with this Code example:-

    in .h Class:-

    @property (nonatomic, strong) NSCache *imageCache;
    

    in .m class:-

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        self.imageCache = [[NSCache alloc] init];
    
        // the rest of your viewDidLoad
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    
         static NSString *cellIdentifier = @"cell";
         NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
         NewsItem *item = [newsItemsArray objectAtIndex:indexPath.row];
         cell.newsTitle.text = item.title;
    
        UIImage *cachedImage =   [self.imageCache objectForKey:item.image];;
        if (cachedImage)
        {
            cell.imageView.image = cachedImage;
        }
        else
        {
            cell.imageView.image = [UIImage imageNamed:@"blankthumbnail.png"];
    
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
                   NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:item.image]];
                   UIImage *image    = nil;
                    if (imageData) 
                         image = [UIImage imageWithData:imageData];
    
                    if (image)
                    {
    
                         [self.imageCache setObject:image forKey:item.image];
                    }
                  dispatch_async(dispatch_get_main_queue(), ^{
                            UITableViewCell *updateCell = [tableView cellForRowAtIndexPath:indexPath];
                            if (updateCell)
                               cell.imageView.image = [UIImage imageWithData:imageData];
                               NSLog(@"Record String = %@",[cache objectForKey:@"image"]);
                      });
              });            
        }
        return cell;
    }
    

提交回复
热议问题