How to addObject of NSMutableDictionary to NSMutableArray in a loop
Asked Answered
B

3

24

I'm having difficulty to add a data structure to an array to create an array of dictionaries from a loop. I just knew that addObject in NSMutableArray only add pointer to it. I would like to know how to achieve my goal.

Here's my code:

NSMutableDictionary *woRows = [[NSMutableDictionary alloc] init];
NSMutableArray *workOrders = [[NSMutableArray alloc] init];
while ([theScanner isAtEnd] == NO)
{
    if ([theScanner scanUpToCharactersFromSet:usSet intoString:&tempCol1] &&
        [theScanner scanString:@"{US}" intoString:NULL] &&
        [theScanner scanUpToCharactersFromSet:usSet intoString:&tempCol2] &&
        [theScanner scanString:@"{US}" intoString:NULL] &&
        [theScanner scanUpToCharactersFromSet:usSet intoString:&tempCol3]&&
        [theScanner scanString:@"{RS}" intoString:NULL])
    {
        [woRows  setValue:tempCol1 forKey:@"hours"];
        [woRows setValue:tempCol2 forKey:@"colMain"];
        [woRows setValue:tempCol3 forKey:@"colAddtl"];

        [workOrders addObject:woRows];
        [woRows release];
    }
}
[tmpString release];
[jobs addObject:workOrders];
[workOrders release];

from the code above, the array workOrders will have duplicates of last objects added only. I stuck here not able to progress to display the correct data.

Any help will be appreciated.

Thanks

Bennet answered 24/12, 2009 at 11:2 Comment(0)
M
27

try doing [workOrders addObject:[woRows copy]];

Minette answered 24/12, 2009 at 11:7 Comment(1)
It worked, and I like your approach and being used in my code. Any idea why I cannot vote to your answer ? It kept changed back to zeroBennet
K
20

I know, this is a bit late and even not what you were asking for, but I guess you wanted to use [woRows setObject:forKey:] instead of [woRows setValue:forKey:].

Kaftan answered 15/9, 2011 at 14:29 Comment(0)
D
7

move your dictionary creation code inside the loop(inside if condition)

woRows = [[NSMutableDictionary alloc] init];

you are using same object...

Defamatory answered 24/12, 2009 at 11:13 Comment(1)
Thank you, it worked. Any idea why I cannot vote to your answer?Bennet

© 2022 - 2024 — McMap. All rights reserved.