Ken*_*rty 9 cocoa-touch objective-c uitableview nsmutabledictionary nsindexpath
有没有为什么试图存储和在检索值什么特别的原因NSMutableDictionary使用NSIndexPath的key可能会失败?
我本来试图这样做是为了保存一个NSMutableDictionary的UITableViewCell高度(self.cellHeights)的UITableView.每次点击a时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];
}
Run Code Online (Sandbox Code Playgroud)
由于我不知道的原因,在tableView:didSelectRowAtIndexPath:通道内获得单元高度[self.cellHeights objectForKey:indexPath]工作正常.但是,尝试获取tableView:heightForRowAtIndexPath:via中的单元格高度[self.cellHeights objectForKey:indexPath]始终返回nil,因为用于存储高度的indexPath似乎与用于获取单元格高度的indexPath不匹配,即使它们具有相同的值indexPath.section和indexPath.row.因此,"相同"索引路径的新对象被添加到self.cellHeights(因为此后self.cellHeights.count增加).
这并没有当您存储使用行(中的NSMutableDictionary细胞高度发生[NSNumber numberWithInteger:indexPath.row])为重点......所以这是我在做什么,现在,但我想知道为什么indexPath不工作的关键.
Jea*_*nan 13
虽然我讨论的时间较晚,但这是一个快速而简单的解决方案,允许您将NSIndexPath实例用作字典键.
只需通过添加以下行重新创建 indexPath:
indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
Run Code Online (Sandbox Code Playgroud)
瞧.tableView:heightForRowAtIndexPath:在NSMutableIndexPath内部使用实例(正如您将看到的断点).不知何故,这些实例NSIndexPath在计算哈希键时似乎不合作.
通过将其转换回一个NSIndexPath,然后一切正常.
@Jean 的回答似乎可以接受,但这里已经更详细地回答了这个问题。简而言之,UITableView有时使用的实例NSMutableIndexPath而不是NSIndexPath这两个类的实例永远不会相等,因为[NSMutableIndexPath class] != [NSIndexPath class]. 解决方法是始终NSIndexPath为依赖于isEqual或 的任何东西生成一个键hash,例如查找字典键:
- (NSIndexPath *)keyForIndexPath:(NSIndexPath *)indexPath
{
if ([indexPath class] == [NSIndexPath class]) {
return indexPath;
}
return [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
}
Run Code Online (Sandbox Code Playgroud)
为了让对象作为 的密钥可靠地工作,必须实现几件事,NSDictionary即和协议。isEqual:hashCopyable
我不太确定它NSIndexPath是否有意用作字典的键(因为它是作为数组的索引)。
我的猜测是,hash该类的不同实例没有正确实现。另请注意,某些表委托方法是用 调用的NSIndexPath,另一些是用 调用的NSMutableIndexPath。这可能就是造成差异的原因。
| 归档时间: |
|
| 查看次数: |
4809 次 |
| 最近记录: |