如何从 NSdictonary - iphone sdk 获取键值

发布于 2024-08-21 18:57:34 字数 728 浏览 7 评论 0原文

我使用一个 API,它为我提供来自网络的数据。数据采用 JSON 格式,存储在 NSDictionary 中。像这样:

SBJSON *parser = [[SBJSON alloc] init];
dict = [[NSDictionary alloc]init];
dict = [parser objectWithString:jsonArray error:nil];

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";
        };
   

如何访问值“1262”和“1993”并将它们放入NSArray ,在 UITableView 中使用?

I use an API which provides me data from the web. The data is in JSON format, and is stored in a NSDictionary. Like this:

SBJSON *parser = [[SBJSON alloc] init];
dict = [[NSDictionary alloc]init];
dict = [parser objectWithString:jsonArray error:nil];

Ggb console result for: 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";
        };
   

How can I access the values "1262" and "1993" and put them in a NSArray, for use in a UITableView?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丘比特射中我 2024-08-28 18:57:34

首先,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.
}

First of all, SBJSON's objectWithString:error: method will return one of the folowing depending on what the root object is in the JSON message:

  • NSArray
  • NSDictionary

So, you shouldn't always assume it'll return you a dictionary unless you know for a fact what will be returned in the JSON.

Secondly, you're allocating a new NSDictionary object, but then assigning the result of the parser to your dict variable, leaking the previously allocated dictionary.
You don't need this line: dict = [[NSDictionary alloc]init];.

Finally, since the returned object is a dictionary, you can get al of the objects out of the dictionary like this:

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

    //do stuff with feed.
}
鲜肉鲜肉永远不皱 2024-08-28 18:57:34
return [dict allKeys];
return [dict allKeys];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文