简体   繁体   中英

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.

最短的方式:

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

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
}];
NSDictionary *semacko = [allCourses objectForKey:@"semacko"];
NSNumber *number = [semacko objectForKey:@"id"];
NSNumber *number = allCourses[@"semacko"][@"id"];

or if you want to iterate all objects:

for(NSDictionary* course in allCourses) {
    NSNumber *number = course[@"id"];
}
NSString *name =[[NSString alloc]initWithFormat:@"%@",[Dictionaryname objectForKey:@"key"]];

通过此代码,您可以访问与objectforkey关键字中指定的键对应的值

You can try:

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

For setting value:

- setValue:forKeyPath:

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