1

我在缓存和显示缓存的图像时遇到问题。这是一个包含大量图像的集合视图。

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";
    CollectionViewCell *cell = (CollectionViewCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    UIImage *imageMP = [_imageCache objectForKey:[self getImage:indexPath.row]];

    NSLog(@"looking for \"%@\"",[self getImage:indexPath.row]);

    if (imageMP) {
         NSLog(@"found it!");
        cell.img_pic.image = imageMP;

    }else{
        //display loading pic so long
        cell.img_pic.image = [UIImage imageNamed:@"photo1.png"];

        [self.queue addOperationWithBlock:^{
            UIImage *image = [self getActualImage:indexPath.row];
            if (image) {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    cell.img_pic.image = image;
                }];
                [_imageCache setObject:image forKey:[self getImage:indexPath.row]];

                NSLog(@"saving as \"%@\"",[self getImage:indexPath.row]);
            }
        }];

    }

它正确加载并显示图像,问题在于保存到缓存然后从缓存中显示。

NSLog 到控制台的输出如下

looking for "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"
saving as   "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"
looking for "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"
saving as   "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"
looking for "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"
saving as   "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"

它永远不会正确显示缓存的图像,否则会打印“找到它!”

我究竟做错了什么?

4

2 回答 2

1

使用 JMCache ( https://github.com/jakemarsh/JMImageCache ) 然后使用以下代码

 [cell.img_pic.image setImageWithURL:[NSURL URLWithString:imageUrl] placeholder:[UIImage imageNamed:@"laoding.png"]];
于 2013-08-26T09:42:12.867 回答
0

这解决了问题。

_imageCache = [[NSCache alloc] init];

我只是忘了分配和初始化 NSCache。

于 2013-08-27T09:03:52.097 回答