Question

I am getting an XML format data from server and parsing it in an scenario. I am having problem putting this data in key, value pair using NSMutableDictionary. Because, NSMutableDictionary key is unique. So, it overwrites the key with the previous value existing if there are same keys are coming from xml. For ex: My XML data is below.

<?xml version='1.0' encoding='utf-8'?><order>
            <number>123</number>
            <detail>

                <name>shoe</name> 
                <description>This is from nike</description>
                <price>10.00</price>

                <name>discount</name> 
                <description>This is from Arrow</description>
                <price>-1.00</price>

                <name>bag</name> 
                <description>This is a leather one</description>
                <price>10.00</price>

            </detail>
          </order>

[appDelegate.finalOrderDict setObject:trimmString forKey:elementName];

I am trying to put the data in key, value pair using NSMutableDictionary, because, i'll be showing the output in another view like below.

Summary:
Shoe     $ 10.00
Discount $ -1.00   
Bag      & 10.00
Discount $ -2.00 

But, as the keys are repeating same, its overwriting the data from the existing one.

Could someone help me resolving duplicating of key in case if there are same keys present in the data and we try to put that in NSDictionary.

Thank you!

Was it helpful?

Solution

NSDictionary is behaving as intended - when -setObject:forKey: is called, an existing key-value pair is overwritten if the old key and the new key respond YES to -isEqual:. It sounds like you need to modify your data structure.

One idea would be having appDelegate.finalOrderDict instead be an NSArray of NSDictionary objects. Each NSDictionary would then have "name" and "price" key-value pairs.

You could also have each value promoted to an array if it already exists:

id existingValue = [appDelegate.finalOrderDict objectForKey:forKey:elementName];
if ([existingValue isKindOfClass:[NSMutableArray class]]) {
    [existingValue addObject:trimmString];
} else if (existingValue) {
    [appDelegate.finalOrderDict setObject:[NSMutableArray arrayWithObjects:existingValue, trimmedString, nil] forKey:elementName];
} else {
    [appDelegate.finalOrderDict setObject:trimmedString forKey:elementName];
}

This approach is riskier, however, as you have to type-check all objects obtained from finalOrderDict, to see if they are strings or arrays.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top