加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

iphone – 我如何迭代并获取NSDictionary中的所有值?

发布时间:2020-12-14 17:18:13 所属栏目:百科 来源:网络整理
导读:我有个问题. 我使用XMLReader类来获取NSDictionary,一切正常.但我无法获取productData元素的属性值. 具体来说,我有以下NSDictionary: {response = { products = { productsData = ( { alias = "Product 1"; id = 01; price = "10"; },{ alias = "Product 2"
我有个问题.

我使用XMLReader类来获取NSDictionary,一切正常.但我无法获取productData元素的属性值.

具体来说,我有以下NSDictionary:

{
response = {
  products = {
   productsData = (
    {
    alias = "Product 1";
    id = 01;
    price = "10";
    },{
    alias = "Product 2";
    id = 02;
    price = "20";
    },{
    alias = "Product 3";
    id = 03;
    price = "30";
  });
 };
};
}

我用这段代码创建了de NSDictionary:

NSDictionary *dictionary = [XMLReader dictionaryForXMLData:responseData error:&parseError];

和responseData包含:

<application>
  <products>
    <productData>
      <id>01</id>
      <price>10</price>
      <alias>Product 1</alias>
    </productData>
    <productData>
      <id>02</id>
      <price>20</price>
      <alias>Product 2</alias>
    </productData>
    <productData>
      <id>02</id>
      <price>20</price>
      <alias>Product 3</alias>
    </productData>
  </products>
</application>

然后,我不知道如何得到每个productData的值,如id,price和别名……

谁知道怎么做?

谢谢,请原谅我的英语不好!

解决方法

从…开始

NSDictionary *dictionary = [XMLReader dictionaryForXMLData:responseData error:&parseError];

你可以这样做:

NSDictionary *application = [dictionary objectForKey:@"application"];
if ([[application objectForKey:@"products"] isKindOfClass [NSArray class]]) {
    NSArray *products = [application objectForKey:@"products"];
    for (NSDictionary *aProduct in products) {
       // do something with the contents of the aProduct dictionary
    }
else if {[[application objectForKey:@"products"] isKindOfClass [NSDictionary class]]) {
    // you will have to see what the returned results look like if there is only one product 
    // that is not in an array,but something along these lines may be necessary
    // to get to a single product dictionary that is returned
}

我有一个与此类似的情况(解析JSON),其中没有为signle值返回数组,因此必须检查数组(在您的情况下是产品词典)或单个NSDictionary(产品字典)在你的情况下).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读