【问题标题】:How to retrieve String from NSDictionary in objective C?如何从目标 C 中的 NSDictionary 中检索字符串?
【发布时间】:2012-06-07 17:31:30
【问题描述】:

我正在尝试检索 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

【问题讨论】:

  • 在获取该键的对象之前,您应该在NSLog 中单独检查您的theString,以查看它是否实际上将其设置为[keys objectAtIndex:row]。也许row 未初始化或未返回所需结果,因此密钥为nilnull

标签: iphone objective-c arrays


【解决方案1】:

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

我发现dictionaryWithObjectsAndKeys: 工厂在大多数情况下更有用,例如:

conversionOptions = [NSDictionary dictionaryWithObjectsAndKeys:@"1.7", @"red", @"2.8", @"blue", nil];

【讨论】:

  • 是的,这行得通!我不敢相信我没有看到,谢谢:)
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    使用objectForKey: 而不是valueForKey:


    当您调用objectForKey: 时,确保conversionOptions 不为零(这是正确的方法)。

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

    不过,您绝对必须使用 objectForKey: valueForKey: 专用于 KVC。

    【讨论】:

    • 这也不起作用,我将更新问题以反映这一点。谢谢
    猜你喜欢
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多