views:

58

answers:

1
nodes = [doc nodesForXPath:@"//user" error: nil];
            for (CXMLElement *node in nodes) {
                [itemPreDict setObject:[[node attributeForName:@"name"] stringValue] forKey:@"name"];
                [itemPreDict setObject:[[node attributeForName:@"gender"] stringValue] forKey:@"gender"];
                [itemPreDict setObject:[[node attributeForName:@"dob"] stringValue] forKey:@"dob"];

                [itemDict setObject:itemPreDict forKey:[[node attributeForName:@"name"] stringValue]];

            }

In the end of loop, I'm getting 10 dicts (10 users) with same info for last user in a list, how can I get 10 dicts with different user info. Help Me Please!

A: 

You are rewriting the same itemPreDict over and over again. To store different info, you need to create 10 different dictionaries. Try

        for (CXMLElement *node in nodes) {
            NSMutableDictionary* itemPreDict = [[NSMutableDictionary alloc] init];
            // ^----------
            [itemPreDict setObject:[[node attributeForName:@"name"] stringValue] forKey:@"name"];
            [itemPreDict setObject:[[node attributeForName:@"gender"] stringValue] forKey:@"gender"];
            [itemPreDict setObject:[[node attributeForName:@"dob"] stringValue] forKey:@"dob"];

            [itemDict setObject:itemPreDict forKey:[[node attributeForName:@"name"] stringValue]];
            // v----------
            [itemPreDict release];
        }

instead.

(Since you need to create a dictionary anyway, use -initWithObjectsAndKeys: instead of calling -setObject: three times. This also allows itemPreDict to be an NSDictionary instead of NSMutableDictionary.)

KennyTM
Thank you! It's works! :)
victor