0

これはおそらくかなり基本的な問題ですが、原因を突き止めることができないので試してみてください。

次のコードを書きました。

    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 ...
    }

この問題objectsForValueは が空のときに発生します。これは常に発生するわけではありませんが、定期的に発生します。私があまり間違っていなければ[NSNumber numberWithInt:someValue]、 Object に に追加されたときに NSNull として解釈されない限り、これは論理的に不可能ですmyDictionaryが、同じ式が NSArray に追加されているときにオブジェクトとして扱われますvalues

そしてロギングするmyDictionaryと、これが実際に起こっていることに気づきました。誰かが私に理由を説明できますか?

4

1 に答える 1

1

と をオーバーライド-isEqual:していない場合-hash、 のコピーはCustomObjectAdoptingNSCopy互いに等しくありません。NSObjectの等価性のデフォルトの実装は、オブジェクト ID です。コピーはキーをコピーしますが、NSDictionaryコピーは元のキーと等しくないため、辞書にキーを要求して使用しない限り、辞書から何も取得できません。オリジナルは機能しません。

于 2013-11-21T21:34:19.660 に答える