我使用 NSMutableDictionary
来存储有关某些 UITableViewCell
的一些值,因此我使用 NSIndexPath
的实例作为键。在 iOS 6 上一切都按预期运行,但是当我在 iOS 5 模拟器中运行完全相同的代码时,奇怪的事情发生了。所以我将字典的内容打印到控制台:
Printing description of heights:
{
"<UIMutableIndexPath 0x6a8a3d0> 2 indexes [1, 3]" = 100;
"<UIMutableIndexPath 0x6a8a3d0> 2 indexes [1, 3]" = 100;
"<UIMutableIndexPath 0x6a8a3d0> 2 indexes [1, 3]" = 100;
}
在 iOS 6 上,它看起来像这样:
Printing description of heights:
{
"<UIMutableIndexPath 0x75ca8c0> 2 indexes [0, 1]" = 44;
"<UIMutableIndexPath 0x75caa70> 2 indexes [0, 0]" = 10;
"<UIMutableIndexPath 0x75ca500> 2 indexes [1, 0]" = 100;
"<UIMutableIndexPath 0x717df70> 2 indexes [1, 1]" = 67;
"<UIMutableIndexPath 0x715a3e0> 2 indexes [1, 2]" = 67;
"<UIMutableIndexPath 0x717def0> 2 indexes [1, 3]" = 67;
}
显然,事情应该是这样的!为什么 iOS 5 上的字典会为完全相同相同的键存储不同的值?
编辑:一些代码...
字典创建只是
self.heights = [[NSMutableDictionary alloc] init];
我使用新的下标语法设置值,即像这样:
self.heights[indexPath] = minHeight;
(indexPath
是一个 NSIndexPath
,minHeight
是一个 NSNumber
。)
我根据委托(delegate)请求动态设置这些值:
- (NSNumber *)heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (![indexPath isInTableView:self.tableView])
{
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"indexPath not in tableView" userInfo:nil];
}
NSNumber *storedHeight = self.heights[indexPath];
if (storedHeight != nil)
{
return storedHeight;
}
NSNumber *minHeight = self.minimumHeights[indexPath];
self.heights[indexPath] = minHeight;
return minHeight;
}
minimumHeights
NSDictionary
还保存 TableView 中每个索引路径的 NSNumber
。
最佳答案
我记得读过关于 NSIndexPath
方法 isEqual:
或 hash
或两者在 iOS6 中发生变化,或者只是 iOS 5 中存在错误。无论如何,您似乎无法将它们用作字典键。
尝试使用不同的键。也许使用其 description
方法或使用部分和行构建的自定义字符串。
#define idx2key(_ip) [NSString stringWithFormat:@"%d:%d", [_ip section], [_ip row]]
...
self.heights[idx2key(indexPath)] = minHeight;
...
在旧的 NSIndexPath
苹果中说:
NSIndexPath objects are uniqued and shared. If an index path containing the specified index or indexes already exists, that object is returned instead of a new instance.
该段落不再存在。我猜实例的内部比较也发生了变化。
关于iphone - iOS 5 上 NSDictionary 中出现奇怪的重复键,而 iOS 6 上则不然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14173510/