質問

This is probably a rather basic problem, but try as I might I can't find the reason that causes it.

I wrote the following code:

    NSMutableDictionary * myDictionary = [[NSMutableDictionary alloc] init];
    NSMutableArray * values = [[NSMutableArray alloc] init];

    for (int i=0; i<10; i++) {

        // create an object that can become a key in an NSDictionary
        CustomObjectAdoptingNSCopy * someKey = [[CustomObjectAdoptingNSCopy alloc] init];

        // create a random value that will become an object for myDictionary ...
        int someValue = rand()%10;

        // ... and which also gets to be an object in the values array, provided it isn't already stored there
        if ([values indexOfObject:[NSNumber numberWithInt:someValue]]==NSNotFound)
            [values addObject:[NSNumber numberWithInt:someValue]];

        // now associate someValue with someKey in myDictionary
        [myDictionary setObject:[NSNumber numberWithInt:someValue] forKey:someKey];
    }

    // read the data in myDictionary enumerating the NSArray values
    for (NSNumber * aValue in values){
        NSArray * objectsForValue = [myDictionary allKeysForObject:aValue];
        // now the data from objectsForValue are being used ...
    }

The problem manifests when objectsForValue is empty, which does not happen all the time but regularly. If I am not very much mistaken this is logically impossible unless [NSNumber numberWithInt:someValue] gets interpreted as NSNull when added as Object to myDictionary, while the same expression gets treated as an object when it is being added to the NSArray values.

And logging myDictionary I noticed that this is indeed what's happening. Can anybody explain to me why?

役に立ちましたか?

解決

If you haven't overridden -isEqual: and -hash, then copies of your CustomObjectAdoptingNSCopy don't equal each other. NSObject's default implementation of equality is object identity. Since NSDictionary copies the keys but copies don't equal the original, you can't retrieve anything from the dictionary unless you ask it for its keys and use those. The originals won't work.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top