如何从NSdictonary获取关键值 - iphone sdk

Bar*_*oon 1 iphone json nsdictionary

我用api向我提供网上的数据.数据采用Json格式,并存储在NSDictionary.像这样:

SBJSON *parser = [[SBJSON alloc] init];
dict = [[NSDictionary alloc]init];
dict = [parser objectWithString:jsonArray error:nil];
Run Code Online (Sandbox Code Playgroud)

Ggb控制台结果:po dict

        1262 =             {
            "feed_name" = name1;
            "new_results" = 6;
            "next_update" = "2010-02-16T15:22:11+01:00";
        };
        1993 =             {
            "feed_name" = name2;
            "new_results" = 0;
            "next_update" = "2010-02-16T09:09:00+01:00";
        };
Run Code Online (Sandbox Code Playgroud)

我如何访问值"1262"和"1993"并将它们放入一个NSArray,用于aUITableView

非常感谢,问候,巴特

Jas*_*ien 5

首先,SBJSON的objectWithString:error:方法将返回以下其中一个,具体取决于JSON消息中的根对象:

  • NSArray的
  • 的NSDictionary

所以,除非你知道将在JSON中返回什么,否则你不应该总是假设它会返回一个字典.

其次,你要分配一个新的NSDictionary对象,然后将解析器的结果分配给你的dict变量,泄漏先前分配的字典.你不需要这一行:dict = [[NSDictionary alloc]init];.

最后,由于返回的对象字典,您可以从字典中获取对象,如下所示:

for (NSString *key in [dict allKeys])
{
    NSDictionary *feed = [dict objectForKey:key];

    //do stuff with feed.
}
Run Code Online (Sandbox Code Playgroud)