How to get key/value pair from NSDictionary?

蓝咒 提交于 2019-12-10 18:16:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!