My latest task in CSCW Lab was to create the parser class for parsing some huge and multilevel XML. All nice and easy at first sight. Since the XML was the result of an RPC call, I got back some structures corresponding to NSDictionary and some arrays corresponding to NSArray in Apple’s Objective-C.
While iterating in the structure using NSXMLParser, a event-based parser, I kept adding the pairs as name and values to the parent.The normal approach would be to add the name and NSNull for value first, then when retrieving the value’s content, search the last inserted entry ( the pair composed by name and value) and just fill the value with content. First I instantiate the strKey with the last key obtained from the array who contains all dictionary keys, then I set the value for the key already computed.The code that I used was :
// get the last element in the dictionary and set it's value NSString *strKey = [[(NSMutableDictionary *)parentObj allKeys] lastObject]; [(NSMutableDictionary *)parentObj setObject:theValue forKey:strKey];
But surprise! the last value is the same always (in my specific case the first added element). What the heck ?
Digging more deeply into this, seems that setObject:ForKey doesn’t ADD at the end of the dictionary, but more randomly insert the elements.