Search code examples
iphoneobjective-cxcodensdictionaryxmlreader

How I can iterate and get all values in a NSDictionary?


I have a problem.

I am using the XMLReader class to get a NSDictionary and everything works fine. But i can't to get the values of the atributes of my productData element.

Specifically, I have the following 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";
  });
 };
};
}

I used this code to create de NSDictionary:

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

and responseData contains:

<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>

Then, i don't know how get the values of each productData like id, price and alias...

Anybody know how to do it??

Thanks and please forgive my bad english !


Solution

  • Starting with

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

    you can do something like this:

    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
    }
    

    I have had a case similar to this (parsing JSON) where an array was not returned for a signle value, so the result had to be checked for both an array (of product dictionaries in your case) or a single NSDictionary (the product dictionary in your case).