【问题标题】:Best way get object for key for inner key in NSDictionary? [duplicate]在 NSDictionary 中获取内部键的键对象的最佳方法? [复制]
【发布时间】:2016-05-13 08:46:31
【问题描述】:

也许这个问题的标题不是很清楚。我的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"];

有没有更好的方法来做到这一点?

【问题讨论】:

标签: ios objective-c


【解决方案1】:

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

[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

【讨论】:

  • 这是最好的办法。
  • setValue:forKey: 虽然不酷...
  • 你的意思是使用setObject:forKey
  • @trojanfoe 那么用什么来代替setValue:forKey
  • 我知道如果我们使用像NSMutableDictionary这样的可变对象,那么我们必须使用setObject:forKey,如果我们使用NSDictionary,那么使用setValue:forKey
【解决方案2】:

使用此代码,

在 body 关键字中更改 objectForKey 而不是 valueForKey,

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

希望对你有帮助

【讨论】:

  • 这是最糟糕的方式。
  • 我是IOS新手,我只使用了以上方法,谢谢您的反馈
猜你喜欢
  • 2011-09-10
  • 2013-05-11
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 2016-03-27
  • 2022-06-16
相关资源
最近更新 更多