2

NSDictionary のキーの値を取得しようとしています。ディクショナリは、両方とも文字列型のキーと値のペアで初期化されています。問題は、objectForKey または valueForKey を呼び出しても値を取得できないように見えることです。

辞書を反復処理して、キーと値の両方を出力できます。

誰かが間違っているところを指摘できますか? これが私のコードです...

//Set up dictionary with options
keys = [NSArray arrayWithObjects:@"red", @"blue", nil];
values = [NSArray arrayWithObjects:@"1.7", @"2.8", nil];

conversionOptions = [NSDictionary dictionaryWithObject:values 
                                                forKey:keys];

次に、これはピッカーの選択行で呼び出されます

NSLog(@"... %@", [keys objectAtIndex:row]);       //prints out the key
NSString *theString = [keys objectAtIndex:row];   //save it as a string
NSLog(@"The string is... %@", theString);         //print it out to make sure im not going crazy

NSLog(@"the value is : %@",[conversionOptions objectForKey:theString]); // I just get NULL here
//NSLog(@"the value is : %@",[conversionOptions valueForKey:theString]); // This doesn't work either, I just get NULL
4

3 に答える 3

9

唯一のキーとして配列を使用し、その値の配列を使用して辞書を作成しています。キー配列の各要素が値配列のそれぞれの要素の個別のキーとして使用されるように、(単一)dictionaryWithObjects:forKeys:ではなく(複数)ファクトリが必要です。dictionaryWithObject:forKey:

dictionaryWithObjectsAndKeys:ほとんどの場合、ファクトリの方が便利だと思います。例:

conversionOptions = [NSDictionary dictionaryWithObjectsAndKeys:@"1.7", @"red", @"2.8", @"blue", nil];
于 2012-06-07T17:35:18.407 に答える
8

これは、辞書オブジェクトから文字列を取得する方法です

NSString * string = [dictionary objectForKey:@"stringKey"];

于 2012-06-07T17:37:44.957 に答える
1

使用しobjectForKey:ないでくださいvalueForKey:


conversionOptions呼び出すときは、非 nil であることを確認してくださいobjectForKey:(これが正しい方法です)。

そして、ええ、derp -- 間違ったファクトリ メソッドが使用されていることを見逃していました。DictionaryWithObjects:andKeys: を実行するか、pmjordan が言ったことを実行できます。

ただし、絶対に使用する必要がobjectForKey:あります。 valueForKey:は KVC に固有です。

于 2012-06-07T17:33:43.530 に答える