缓存以NSIndexPath为键返回错误的objectForKey

时间:2013-01-10 22:37:00

标签: ios objective-c uitableview nsindexpath nscache

在我的cellForRowAtIndexPath方法中,我有以下代码:

if ([self.cellImageCache objectForKey:indexPath]) {
        UIImage *image = [self.cellImageCache objectForKey:indexPath];
        [cell.entryView setImage:image];

        return cell;
    }

Entry *entry = [self.appDelegate.fetchedResultsController objectAtIndexPath:indexPath];

UIImage *image = [JTimelineCellContent imageForEntry:entry];

[cell.entryView setImage:image];

[self.cellImageCache setObject:image forKey:indexPath];

当我滚动到tableview的底部时,每个单元格显示正常。向上滚动时,单元格也显示正常。但是当我向上滚动向上滚动后,细胞开始重复出现。

我为索引路径进行的每次NSLog搜索都会返回正确的值,即使在重复的单元格上也是如此。

1 个答案:

答案 0 :(得分:1)

NsIndexPath实际上是一个数组而不是字符串。 所以你的设计存在缺陷。

您可以通过使用以下内容从indexPath生成唯一字符串:

NSString *uniqueKey = [NSString stringWithFormat:@"key%@%@",indexPath.section,indexPath.row];

所以你可以:

NSString *uniqueKey = [NSString stringWithFormat:@"key%@%@",indexPath.section,indexPath.row];
  if ([self.cellImageCache objectForKey:uniqueKey]) {
            UIImage *image = [self.cellImageCache objectForKey:uniqueKey];
            [cell.entryView setImage:image];

            return cell;
        }

    Entry *entry = [self.appDelegate.fetchedResultsController objectAtIndexPath:indexPath];

    UIImage *image = [JTimelineCellContent imageForEntry:entry];

    [cell.entryView setImage:image];

    [self.cellImageCache setObject:image forKey:uniqueKey];