从NSDictionary获取值时出错

时间:2017-03-02 23:18:48

标签: ios objective-c xcode nsdictionary unrecognized-selector

我试图从NSDictionary解析的JSON中获取,并且我一直都会收到此错误。

的NSDictionary:

{
    "admin_id" = 191767626;
    body = "\U043a\U043b\U0430\U0441\U0441, \U043f\U043e\U0447\U0442\U0438 \U0434\U043e\U0434\U0435\U043b\U0430\U043b \U043f\U043e\U0434\U0434\U0435\U0440\U0436\U043a\U0443 \U0433\U0440\U0443\U043f\U043f\U043e\U0432\U044b\U0445 \U0431\U0435\U0441\U0435\U0434";
    "chat_active" = "191767626,111273042,108237840,178159348,119271375,90588741,131506543,12657348,251374070,77508447,257350143,222456587,133059311,119425760,95255813,138571437,183017202,57733104,277277624,166958749,138127148,146374071,26326487,71995910,141152531,169957302,148888167,350803848,381660274,94296816,388139636";
    "chat_id" = 104;
    date = 1488494694;
    mid = 1141349;
    out = 1;
    "photo_100" = "https://pp.userapi.com/c637621/v637621626/2317d/K9M4thCXrP0.jpg";
    "photo_200" = "https://pp.userapi.com/c637621/v637621626/2317b/u5opnbkPQo0.jpg";
    "photo_50" = "https://pp.userapi.com/c637621/v637621626/2317e/tNBXXHah700.jpg";
    "push_settings" =         {
        "disabled_until" = 1773859745;
        sound = 0;
    };
    "read_state" = 1;
    title = CJB;
    uid = 79372051;
    "users_count" = 32;
}

因此,我有兴趣获取密钥chat_idtitleusers_count

的值

我试过

NSLog(@"%@", [chatInfo objectForKey:@"chat_id"]);

但我收到此错误

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber objectForKey:]: unrecognized selector sent to instance 0x19478910'

我该如何解决这个问题?提前谢谢!

2 个答案:

答案 0 :(得分:1)

Try like this :

NSLog(@"%@", [[chatInfo objectForKey:@"chat_id"] stringValue]);

Or

NSLog(@"%@",[NSString stringWithFormat:@"%@", [[chatInfo objectForKey:@"chat_id"] stringValue]]);

Hope this will work for you.

答案 1 :(得分:0)

Try this and use breakpoints on NSLogs for understand what is wrong:

if ([chatInfo isKindOfClass:[NSArray class]]) {
  NSArray *array = (NSArray *) chatInfo;
  [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if ([destinationVC isKindOfClass:[NSDictionary class]]) {
      NSDictionary *dictionary = (NSDictionary *) destinationVC;
      if (dictionary[@"chat_id"]) {
        NSLog(@"chat_id: %@", dictionary[@"chat_id"]);
      } else {
        NSLog(@"chat_id: not found");
      }
    } else {
      NSLog(@"its not dictionary, check your JSON mapping");
    }
  }];
} else {
  NSLog(@"This is not NSArray!");
}