带有自定义键的NSDictionary行为奇怪 - 值偶尔会变为null和back

时间:2013-12-28 11:26:11

标签: objective-c dictionary null

我遇到了NSMutableDictionary的问题,我正在使用键的自定义对象类型通过循环填充。我已经实现了NSCopying所以我希望一切都好。看着循环的结果,我注意到键似乎没问题,但是这些值非常奇怪地进出NULL。每次迭代时字典的控制台输出:

{
    "C#-10" = "<SWPP_BeamModel: 0xc4ba470>";
    "D-10" = "<SWPP_BeamModel: 0xc4b5600>";
    "C-10" = "<SWPP_BeamModel: 0x1277f810>";
}
// ...ok so far

{
    "C#-10" = "<SWPP_BeamModel: 0xc4ba470>";
    "C-10" = "<SWPP_BeamModel: 0x1277f810>";
    "D#-10" = (null);
    "D-10" = "<SWPP_BeamModel: 0xc4b5600>";
}
// ...oops a null

{
    "C#-10" = "<SWPP_BeamModel: 0xc4ba470>";
    "C-10" = "<SWPP_BeamModel: 0x1277f810>";
    "D#-10" = (null);
    "D-10" = "<SWPP_BeamModel: 0xc4b5600>";
    "E-10" = (null);
}
// ...and another

{
    "C#-10" = "<SWPP_BeamModel: 0xc4ba470>";
    "C-10" = "<SWPP_BeamModel: 0x1277f810>";
    "D#-10" = (null);
    "F-10" = (null);
    "D-10" = "<SWPP_BeamModel: 0xc4b5600>";
    "E-10" = "<SWPP_BeamModel: 0x1277fad0>";
}
// ...another but value for key "E-10" is back!

它继续这样。最后的关键是这条线......

// De-mutablise
_noteBeamsMap = [NSDictionary dictionaryWithDictionary:beamsMap];

这导致_noteBeamsMap

{
    "D#9" = (null);
    G1 = (null);
    C14 = (null);
    "G-7" = (null);
    ...

是什么给出了?

1 个答案:

答案 0 :(得分:1)

事实证明,我在自定义密钥类中实现了isEqual:,但未在hash中进行匹配。简而言之,in this helpful blog post hash需要在isEqual:返回YES时返回相同的值。