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++指针和引用的选择最近在看...
关于vtordisp知多少?我相信不少人看到这篇文章,多半是来自...
那些陌生的C++关键字学过程序语言的人相信对关键字并...
命令行下的树形打印最近在处理代码分析问题时,需要将代码的...
虚函数与虚继承寻踪封装、继承、多态是面向对象语言的三大特...