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调用时非零objectForKey:(这是正确的方法)。

而且,是的,derp——我错过了使用错误的工厂方法。你可以做 dictionaryWithObjects:andKeys: 或者做 pmjordan 所说的。

但是,您绝对必须使用objectForKey: valueForKey:特定于 KVC。

于 2012-06-07T17:33:43.530 回答