如何从目标C中的NSDictionary中检索String?

BON*_*BON 2 arrays iphone objective-c

我试图检索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];
Run Code Online (Sandbox Code Playgroud)

然后在选择器中的选择行上调用它

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
Run Code Online (Sandbox Code Playgroud)

pmd*_*mdj 9

您正在创建一个字典,其中数组是唯一的键,而数组是其值!您需要dictionaryWithObjects:forKeys:(复数)工厂,而不是dictionaryWithObject:forKey:(单数),以便keys数组的每个元素将用作values数组的相应元素的不同键.

我发现dictionaryWithObjectsAndKeys:工厂大部分时间都更有用,例如:

conversionOptions = [NSDictionary dictionaryWithObjectsAndKeys:@"1.7", @"red", @"2.8", @"blue", nil];
Run Code Online (Sandbox Code Playgroud)


Fer*_*tes 8

这是从字典对象中检索字符串的方法

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