Martin
Martin

Reputation: 716

How to get key/value pair from NSDictionary?

I need little help with NSDictionary. How can I get 1 pair, lets say a value for "id" if I have dictionary

NSDictionary *allCourses = [NSJSONSerialization JSONObjectWithData:allCoursesData options:NSJSONReadingMutableContainers error:&error];

and it looks like this:

NSDictionary allCourses

Thanks for Your help.

Upvotes: 3

Views: 12940

Answers (6)

Lal Krishna
Lal Krishna

Reputation: 16160

You can try:

NSNumber *courseID = [allCourses valueForKeyPath:@"semacko.id"];

For setting value:

- setValue:forKeyPath:

Upvotes: 0

SARATH SASI
SARATH SASI

Reputation: 1415

NSString *name =[[NSString alloc]initWithFormat:@"%@",[Dictionaryname objectForKey:@"key"]];

by this code you can access the value that corresponds to the key that specified in the objectforkey keyword

Upvotes: 1

LML
LML

Reputation: 1669

Try this:

NSDictionary *allCourses = [NSJSONSerialization JSONObjectWithData:allCoursesData options:NSJSONReadingMutableContainers error:&error];
        [allCourses enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
    // do something with key and obj
}];

Upvotes: 2

Oleg Fedorov
Oleg Fedorov

Reputation: 337

NSNumber *number = allCourses[@"semacko"][@"id"];

or if you want to iterate all objects:

for(NSDictionary* course in allCourses) {
    NSNumber *number = course[@"id"];
}

Upvotes: 1

Avt
Avt

Reputation: 17043

The shortest way:

NSNumber *number = allCourses[@"semacko"][@"id"];

Upvotes: 9

Avi Tsadok
Avi Tsadok

Reputation: 1843

NSDictionary *semacko = [allCourses objectForKey:@"semacko"];
NSNumber *number = [semacko objectForKey:@"id"];

Upvotes: 1

Related Questions