缓存的图像,并且UICollectionView(Caching an Image and UICo

2019-07-05 02:56发布

我是很新,Objective-C的,所以希望这一切才有意义。 我已经下载从服务器的图像和在图像视图显示了他们collectionView cellForItemAtIndexPath:方法。 我现在面临的问题是,图像不会出现被缓存。 它看起来每一个单元被重新使用的时间一样,从服务器相关的图像被重新下载。

在我viewDidLoad方法中,我创建的NSMutableDictionary:

imageDictionary = [[NSMutableDictionary alloc]initWithCapacity:50.0];

从阅读的文档和看答案,我认为这类似的问题,再加上下面的代码就足够了。 我一直在这几天的,我知道有我丢失的东西,或者说我抓的概念。

#pragma mark - UICollectionView Data Source
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;{
    NSLog(@"Begin retrieving photos");
    return [self.photos count];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];
    cell.imageView.image = nil;

    if (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];
        [imageDictionary setObject:image forKey:@"Image"];

        dispatch_async(dispatch_get_main_queue(), ^{
            cell.imageView.image = [imageDictionary objectForKey:@"Image"];
            [cell setNeedsDisplay];
        });
    });
    }
    return cell;
}

任何帮助将不胜感激。 提前致谢。

Answer 1:

@yuf - 再次感谢方向。 NSCache似乎得到我的结果我是后。 这是正常工作的代码。 如果任何人有类似的问题,你可以比较下面我原来的问题。

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


文章来源: Caching an Image and UICollectionView