iphone - iOS 5 上 NSDictionary 中出现奇怪的重复键,而 iOS 6 上则不然

标签 iphone objective-c ios uitableview nsdictionary

我使用 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 是一个 NSIndexPathminHeight 是一个 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/

相关文章:

iPhone - 比较一个 nil NSString 与另一个有值(value)的 NSString 返回 NSOrderedSame

iphone - 无法使用 iCloud 存储在 GridView 中显示图像?

ios - SpriteKit 游戏中的风筝深度

ios - 什么 iOS 版本支持 NSTimer 有效属性?

ios - XCode 7 如何固定到 super View 而不是播放指南

iphone - 如何在 Iphone SDK 中提高搜索速度

ios - 保存和加载 NSMutableArray - NSUserDefaults

objective-c - 将方法的所有参数传递到 NSLog

objective-c - 如何在 iOS 中集成 XMPP 扩展 XEP 0136 以进行聊天存档

objective-c - 如何在 iOS 应用程序中启用多点触控?