简体   繁体   English

如何使用objectForKey访问NSDictionary中的数据

[英]How to access data in a NSDictionary with objectForKey

I'm trying to access the data in a dictionary. 我正在尝试访问字典中的数据。 I'm able to access the data when it's a string like: 当它是一个字符串时,我可以访问数据:

cell.textLabel.text = [[item objectForKey:@"merchant"]objectForKey:@"name"];

but am not sure about the syntax for an NSNumber: 但不确定NSNumber的语法:

NSNumber* latFromTable = [[displayItems objectAtIndex:indexPath.row]
                                           [objectForKey:@"coords"]objectForKey:@"lat"];

I know I'm using NSStrings in the code above which won't work. 我知道我在上面的代码中使用NSStrings,将无法正常工作。 How would I change that to work with NSNumber? 我如何将其更改为与NSNumber一起使用?

the data in the dictionary is presented as the following. 字典中的数据如下所示。 The objectForKey is "coords". objectForKey是“ coords”。 I want access to item 1 and 2 (lat and lng) 我想访问项目1和2(经纬度)

 "coords": {
        "lat": 52.5032,
        "lng": 13.3445

thanks for any help. 谢谢你的帮助。

The Issue with the following code is mismatching of brackets: 以下代码的问题是括号不匹配:

NSNumber* latFromTable = [[displayItems objectAtIndex:indexPath.row]
                                           [objectForKey:@"coords"]objectForKey:@"lat"];

So change it like: 因此,将其更改为:

float latFromTable = (float)[[[displayItems objectAtIndex:indexPath.row]
                                           objectForKey:@"coords"]objectForKey:@"lat"];
NSNumber *value = [NSNumber numberWithFloat:latFromTable];

Try it like this: 像这样尝试:

float latFromTable = [[[displayItems objectForIndex:indexPath.row]
                                       [objectForKey:@"coords"]objectForKey:@"lat"] floatValue];

A key-value pair within a dictionary is called an entry. 字典中的键值对称为条目。 Each entry consists of one OBJECT that represents the key and a second OBJECT that is that key's value. 每个条目都包含一个代表键的对象和另一个代表键值的对象。

NSInteger is not an object (it is just an int value). NSInteger不是对象(它只是一个int值)。

So, you cannot to do it 所以你做不到

---ADDED As schubam proposed, you can receive an NSString and call floatValue. --- ADDED如schubam所建议的,您可以接收NSString并调用floatValue。

---ADDED2 I have read the log more accurately. --- ADDED2我已经更准确地阅读了日志。 You have an object with lat and long attributes. 您有一个具有经度和纬度属性的对象。 So, it is not a second-level dictionary. 因此,它不是第二级字典。 Try to receive the inteface name and get object of these interface. 尝试接收接口名称并获取这些接口的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM