0
votes

I have an NSMutableArray that contains several NSMutableDictionary object, each dict has a NSString and an NSMutableArray in it.

My problem is that I need to find the correct dict based on a string match and when found insert an object into the NSMutableArray in the same dict where the string match was found, I can only make this work the first time when the array is empty because after that I am unable to match the correct string:

Here is what I have tried so far, I tried using contains object but that wont get me inside the dict inside the array so I am stuck

NSMutableArray *variantOptions = [[NSMutableArray alloc] init];    

for (NSDictionary *variant in variantInfo) {
  NSMutableDictionary *variantOption = [[NSMutableDictionary alloc] init];
  NSMutableArray *variantOptionValues = [[NSMutableArray alloc] init];

  NSString *name = variant[@"name"];
  NSString *value = variant[@"value"];

  if(variantOptions.count > 0) {
  // Need to loop through the array until  name isEquaToString variantOptionName and when true insert value into variantOptionValuesArray in that same dict and if not exists create a new dict and insert in array
  } else {
     [variantOptionValues addObject:value];
     [variantOption setObject:name forKey:@"variantOptionName"];
     [variantOption setObject:variantOptionValues forKey:@"variantOptionValues"];
  }
  [variantOptions addObject:variantOption];
}
1
I am not sure exactly what you are trying to do, but your code will obviously not work. First time through the loop, the "if" statement will be false, and you will add some a dictionary entry to the array variantOptions. From then on, the array variantOptions will not be empty, and the "if" statement will be true, and won't do anything - unless you comment is intended to be placeholder for more code. Not clear to me. - Larry
Exactly the comments Is a placeholder for the code I am trying to write but I cannot get my head around how I can reach into the dict inside the array and compare the NSString in the first place - Matt Douhan

1 Answers

-1
votes
for (NSDictionary *variant in variantInfo) {
    NSString *name = variant[@"name"];
    NSString *value = variant[@"value"];

    BOOL found = false;
    for (NSMutableDictionary *v in variantOptions) {
        if (v[@"name"] isequalToString:name]) {
            NSMutableArray *values = v[@"variantOptionValues"];
            [values addObject:value];
            found = true;
            break;
        }
    }

    if (!found) {
        // name was not found
        NSMutableDictionary *variantOption = [[NSMutableDictionary alloc] init];
        NSMutableArray *variantOptionValues = [NSMutableArray alloc] init];

        [variantOptionValues addObject:value];
        [variantOption setObject:name forKey:@"variantOptionName"];
        [variantOption setObject:variantOptionValues forKey:@"variantOptionValues"];
        [variantOptions addObject:variantOption];
     }

}