objective-c – 使用NSIndexPath作为NSMutableDictionary中的关键字的问题?

有没有什么特别的原因为什么尝试使用NSIndexPath作为密钥存储和检索NSMutableDictionary中的值可能会失败?

我最初尝试这样做,以便为UITableView存储一个UITableViewCell高度(self.cellHeights)的NSMutableDictionary.每次点击UITableViewCell,该单元格将根据存储在该特定indexPath的NSMutableDictionary中的值在两个不同的高度之间展开或缩小:

- (CGFloat)tableView:(UITableView *)tableView 
           heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    NSNumber *heightNSNumber = [self.cellHeights objectForKey:indexPath];
    if (!heightNSNumber)
    {
        heightNSNumber = [NSNumber numberWithFloat:100.0];
        [self.cellHeights setobject:heightNSNumber forKey:indexPath];
    }
    return [heightNSNumber floatValue];
}

- (void)tableView:(UITableView *)tableView  
        didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSNumber *heightNSNumber = [self.cellHeights objectForKey:indexPath];
    if (!heightNSNumber)
    {
        heightNSNumber = [NSNumber numberWithFloat:100.0];
        [self.cellHeights setobject:heightNSNumber forKey:indexPath];
    }

    if ([heightNSNumber floatValue] == 100.0)
    {
        [self.cellHeights setobject:[NSNumber numberWithFloat:50.0] 
                             forKey:indexPath];
    } else {
        [self.cellHeights setobject:[NSNumber numberWithFloat:100.0] 
                             forKey:indexPath];
    }
    [tableView beginUpdates];
    [tableView endUpdates];
}

由于我不知道的原因,通过[self.cellHeights objectForKey:indexPath]获取单元格的高度在tableView:didSelectRowAtIndexPath:工作正常.但是,尝试获取tableView中的单元格高度:heightForRowAtIndexPath:通过[self.cellHeights objectForKey:indexPath]总是返回nil,因为似乎用于存储高度的indexPath与用于获取单元格高度的indexPath不匹配,即使它们对indexPath.section和indexPath.row具有相同的值.因此,将“相同”索引路径的新对象添加到self.cellHeights中(显而易见,因为self.cellHeights.count此后增加).

当您使用行([NSNumber numberWithInteger:indexPath.row])将单元格高度存储在NSMutableDictionary中时,这不会发生,所以这是我现在在做的,但是我想了解为什么indexPath不工作的关键.

解决方法

虽然我讨论迟到,这里是一个快速简单的解决方案,可以让您使用NSIndexPath实例作为字典键.

只需通过添加以下行重新创建indexPath:

indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];

瞧. tableView:heightForRowAtIndexPath:内部使用NSMutableIndexPath实例(就像使用断点看到的那样).不知何故,在计算哈希键时,这些实例似乎与NSIndexPath不协调.

通过将其转换回NSIndexPath,那么一切正常.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...