尝试在中存储和检索值是否有任何特殊原因NSMutableDictionary
使用一个NSIndexPath
as a key
可能会失败?
我最初尝试这样做是为了存储NSMutableDictionary
of UITableViewCell
高度(self.cellHeights
) for a UITableView
。每次您点击UITableViewCell
,该单元格将根据存储在中的值在两个不同高度之间膨胀或收缩NSMutableDictionary
对于那个特定的indexPath
:
- (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];
}
由于我不知道的原因,将细胞高度控制在tableView:didSelectRowAtIndexPath:
via [self.cellHeights objectForKey:indexPath]
工作得很好。但是,尝试将单元格高度控制在tableView:heightForRowAtIndexPath:
via [self.cellHeights objectForKey:indexPath]
总是返回 nil,因为似乎用于存储高度的 indexPath 与用于获取单元格高度的 indexPath 不匹配,即使它们具有相同的值indexPath.section
and indexPath.row
。因此,“相同”索引路径的新对象被添加到self.cellHeights
(显而易见,因为self.cellHeights.count
此后增加)。
这确实not当您使用行 ( 将单元格高度存储在 NSMutableDictionary 中时会发生[NSNumber numberWithInteger:indexPath.row]
)作为关键...这就是我现在正在做的事情,但我想了解为什么indexPath
不作为关键。
虽然我在讨论中迟到了,但这里有一个快速而简单的解决方案,它允许您使用 NSIndexPath 实例作为字典键。
Just recreate通过添加以下行来索引路径:
indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
Voilà. tableView:heightForRowAtIndexPath:
uses NSMutableIndexPath
内部实例(正如您在断点中看到的那样)。不知何故,这些实例似乎不与NSIndexPath
计算哈希键时。
通过将其转换回NSIndexPath
,然后一切正常。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)