问题
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:
Thanks for Your help.
回答1:
The shortest way:
NSNumber *number = allCourses[@"semacko"][@"id"];
回答2:
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
}];
回答3:
NSDictionary *semacko = [allCourses objectForKey:@"semacko"];
NSNumber *number = [semacko objectForKey:@"id"];
回答4:
NSNumber *number = allCourses[@"semacko"][@"id"];
or if you want to iterate all objects:
for(NSDictionary* course in allCourses) {
NSNumber *number = course[@"id"];
}
回答5:
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
回答6:
You can try:
NSNumber *courseID = [allCourses valueForKeyPath:@"semacko.id"];
For setting value:
- setValue:forKeyPath:
来源:https://stackoverflow.com/questions/21824528/how-to-get-key-value-pair-from-nsdictionary