Pregunta

So long story short, there's a discrepancy between the output of a NSMutableDictionary's contents and the result of calling allValues on the same object. Below is some debugger output after inspecting the object which demonstrates my problem: (made generic of course)

(lldb) po self.someDict.allKeys
<__NSArrayI 0xa5a2e00>(
    <SomeObject: 0xa5a2dc0>,
    <SomeObject: 0xa5a2de0>
)

(lldb) po self.someDict.allValues
<__NSArrayI 0xa895ca0>(
    0.5,
    0.5
)

(lldb) po self.someDict
{
    "<SomeObject: 0xa5a2dc0>" = (null);
    "<SomeObject: 0xa5a2de0>" = (null);
}

So as we can see, the actual output of the NSMutableDictionary contains null values for both its entries, but the contents of .allValues contains the proper data. These three outputs were taken at the same time in execution.

I'm not sure why this is happening, but I think it may have something to do with the fact that I'm encoding/decoding the object which this dictionary is a property of using CoreData. I believe I'm doing this properly:

[aCoder encodeObject:self.someDict forKey:@"someDict"];

and to decode

self.someDict = [aDecoder decodeObjectForKey:@"someDict"];

The weird thing is that if I inspect the dictionary before it ever gets encoded, it is still in the state described at the beginning of the post, so this is why I'm doubtful the CoreData actions are screwing with the contents.

As always, please don't hesitate to request additional information.

EDIT: The problem was as answered below. I was using a custom class which didn't cooperate with isEqual, so my solution was to change the storage and structure of my logic, which made using a Dictionary unnecessary.

¿Fue útil?

Solución

I have not been able to duplicate the problem using NSString as keys and NSNumber as values. I suspect that your custom class does not properly implement hash and/or isEqual. Specifically, the results from those two methods must be consistent, meaning that if isEqual returns true, then the hash values for the two objects must be identical.

You also need to ensure that your class implements NSCopying properly and that a copy is equal to the original.

Otros consejos

As a general rule, don't use custom objects for dictionary keys. Just use strings and be done with it.

As user3386109 points out, custom objects must properly implement the -hash and -isEqual methods in order to be used as dictionary keys, and even then, custom objects don't work correctly for dictionary keys for things like key/value coding.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top