Darren
Darren

Reputation: 1712

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?

Upvotes: 1

Views: 1276

Answers (2)

Sixten Otto
Sixten Otto

Reputation: 14816

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

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 992955

In the line:

NSMutableDictionary *newdict = [item mutableCopy];

you are creating a copy of the item, and then modifying the copy. Instead, just modify item directly:

[item setObject:[NSDate date] forKey:@"versiondate"];

I see what you're trying to do with item = newdict but that would just change the object that the local pointer item points to, and wouldn't change the actual item in dictionary.

Upvotes: 1

Related Questions