开发者

for loop in iPhone

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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜