hanumanDev
hanumanDev

Reputation: 6614

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.

Upvotes: 0

Views: 1228

Answers (3)

schubam
schubam

Reputation: 46

Try it like this:

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

Upvotes: 1

Midhun MP
Midhun MP

Reputation: 107141

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];

Upvotes: 2

Ivan Surzhenko
Ivan Surzhenko

Reputation: 149

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.

Upvotes: 0

Related Questions