在NSDictionary中获取内键的键的最佳方法是什么?

时间:2016-05-13 08:46:32

标签: ios objective-c

也许这个问题标题不是很清楚。我有以下json:

// {
//    "aps": {
//        "alert": {
//            "title":"nice title",
//            "body":"A nice body. $savings"
//        },
//        "content-available":"1"   //This flag set enables background processing
//    },
//    "blabla":"1",
//    "spend_amount":"$cash",
//    "save_amount":"$savings"
// }           

要获取标题内的信息,我需要执行以下操作:

 NSString * _message = [[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"];

或定义三个两个变量

id payload = [userInfo objectForKey:@"aps"];
id alert = [payload objectForKey:@"alert"];
NSString * _actionTitle = [alert objectForKey:@"title"];

有没有更好的方法呢?

2 个答案:

答案 0 :(得分:3)

尝试使用以下一行代码获取嵌套的Dictionary键值:

[userInfo valueForKeyPath:@"aps.alert.title"];

我只是创建和示例并测试代码:

    NSMutableDictionary *d =[[NSMutableDictionary alloc]init];
    [d setValue:@"A nice body. $savings" forKey:@"body"];
    [d setValue:@"nice title" forKey:@"title"];


    NSMutableDictionary *b =[[NSMutableDictionary alloc]init];
    [b setValue:d forKey:@"alert"];

    NSMutableDictionary *e =[[NSMutableDictionary alloc]init];

    [e setValue:@"1" forKey:@"content-available"];
    [e setValue:b forKey:@"aps"];

    NSLog(@"Dictioarn = %@",e);
    NSLog(@"Dictioarn = %@",[e valueForKeyPath:@"aps.alert.title"]);

输出为

Dictioarn = nice title

答案 1 :(得分:0)

使用此代码,

在body关键字

中更改objectForKey而不是valueForKey
NSString * _message = [[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] valueForKey:@"body"];

希望它有用