I am using a for loop to loop though and insert data into a NSMutableDictionary and then inserting that NSMutableDictionary into an NSMutableArray, the code is fairly simple and shown below:
for (NSDictionary *selectedOption in selectedOptions) {
NSString *name = selectedOption[@"name"];
NSString *value = selectedOption[@"value"];
[variantRow setObject:name forKey:@"name"];
[variantRow setObject:value forKey:@"value"];
[variantInfo addObject:variantRow];
}
The problem I am trying to solve is that *name and *value always gets the last value of the loop even for previously inserted dicts into the variantInfo NSMutableArray, I am assuming my problem is because I am inserting pointers etc, but I don't understand how else I can do it? I need to insert the values and have future inserts not affect previous ones.
I hope the description makes sense as its not to easy to explain.
You are modifying the same NSDictionary
object reference(variantRow
) in every iteration and appending it to the array variantInfo
. You need to create a new NSDictionary object:
for (NSDictionary *selectedOption in selectedOptions) {
NSString *name = selectedOption[@"name"];
NSString *value = selectedOption[@"value"];
if(name && value) {
NSDictionary* newVariantRow = @{"name": name, @"value":value};
[variantInfo addObject: newVariantRow];
}
}