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

前端之家收集整理的这篇文章主要介绍了iphone – 我如何迭代并获取NSDictionary中的所有值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_301_6@ 我有个问题.

我使用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(产品字典)在你的情况下).

猜你在找的Xcode相关文章