简体   繁体   中英

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* latFromTable = [[displayItems objectAtIndex:indexPath.row]
                                           [objectForKey:@"coords"]objectForKey:@"lat"];

I know I'm using NSStrings in the code above which won't work. How would I change that to work with NSNumber?

the data in the dictionary is presented as the following. The objectForKey is "coords". I want access to item 1 and 2 (lat and lng)

 "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).

So, you cannot to do it

---ADDED As schubam proposed, you can receive an NSString and call floatValue.

---ADDED2 I have read the log more accurately. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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