Caching an Image and UICollectionView

后端 未结 1 1828
星月不相逢
星月不相逢 2020-12-16 23:32

I\'m pretty new to Objective-C so hopefully this all makes sense. I\'ve downloaded images from a server and have displayed them in an image view in the collectionView

相关标签:
1条回答
  • 2020-12-17 00:26

    @yuf - thanks again for the direction. NSCache seems to be getting me the results I was after. Here is the code that is working properly. If anyone has a similar issue, you can compare the following to my original question.

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;{
        CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];
    
        NSString *imageName = [[self.photos objectAtIndex:indexPath.row] objectForKey:@"fullimage"];
        UIImage *image = [imageCache objectForKey:imageName];
    
        if(image){
    
            cell.imageView.image = image;
        }
    
        else{
    
        cell.imageView.image = nil;
    
        dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL);
        dispatch_async(downloadQueue, ^{
    
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[self.photos objectAtIndex:indexPath.row] objectForKey:@"fullimage"]]];
            UIImage *image = [UIImage imageWithData:data];
    
            dispatch_async(dispatch_get_main_queue(), ^{
    
                cell.imageView.image = image;
    
            });
    
            [imageCache setObject:image forKey:imageName];
        });
        }
    
        return cell;
    }
    
    0 讨论(0)
提交回复
热议问题