Search code examples
iosxcodensmutabledictionary

Iterate through NSMutableDictionary and change value


Thanks for any help with the following:

I'm loading the following JSON data ..

(
    {
    name = Facilities;
    versiondate = "1972-01-01";
},
    {
    name = Services;
    versiondate = "1972-01-01";
},
    {
    name = ThingsToDo;
    versiondate = "1972-01-01";
}
)

into the following code:

NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:updateData options:kNilOptions error:&errorString];

I am then trying to iterate over the Dictionary and trying to change the versiondate to today's date. I have spent over two hours trying to do this ... and no luck! I'm fighting with trying to also understand MutableCopies etc. I'm relatively new at this ...

So, I'm trying the following:

for (NSMutableDictionary *item in dictionary)
{
    NSMutableDictionary *newdict = [item mutableCopy];
    NSLog(@"I have item as: %@",newdict);
    NSLog(@"I have the date as: %@", [newdict objectForKey:@"versiondate"]);
    [newdict setObject:[NSDate date] forKey:@"versiondate"];
    NSLog(@"I now have the date as: %@", [newdict objectForKey:@"versiondate"]);
    NSLog(@"I have item as: %@",newdict);
    item = newdict;
}

NSLog(@"New Dictionary now becomes: %@", dictionary);

And ignoring the NSLog stuff, I'm having no luck. I'm just trying to change the versiondate to today's date and then save it for each versiondate. Sigh.

Any help to tell me where my "obvious" error is would be appreciated. I'm declaring item as NSMutableDictionary ... so why do I have to then define newdict? And once I've updated the value, how do I "save" this back into my original dictionary?


Solution

  • If you want mutable dictionaries and arrays when you deserialize the JSON, pass the option NSJSONReadingMutableContainers. Otherwise, what comes out is not mutable. And treating it as such will result in the NSInternalInconsistencyException you're seeing.

    You can create mutable copies of the sub-dictionaries, as in the code you show, but that doesn't change the original top-level container's contents. (And assigning the copy back to the original variable at the bottom of your loop accomplishes exactly nothing.)