Andreas Eriksson
Andreas Eriksson

Reputation: 9027

Cast NSDictionary to as Mutable

I have an iPhone application that makes use of an API. Among the API calls, there's one that returns a JSON Dictionary with 3 arrays, each of them containing a set of dictionaries.

Here's how i'm using it:

NSMutableDictionary * allthethings [self FetchAllTheThings]; // Returns the big dictionary

NSMutableArray * oneofthethings = [NSMutableArray arrayWithArray: [allthethings valueForKey:@"First"]];

etc etc.

Then when I'm looping through the "oneofthethings" array and setting a new value on one of the dicts i get a SIGABRT, presumably because the dictionaries contained within are not mutable.

So my question is this: Is there any way to sort of tell the array to store them as mutables? Or will i have to loop through it and copy each of the dictionaries to a mutable analog?

Upvotes: 1

Views: 2306

Answers (4)

FactoryAidan
FactoryAidan

Reputation: 2584

NSMutableDictionary from NSDictionary


Example: Use the mutableCopy method on your NSDictionary

NSMutableDictionary *YOUR_MUTABLE_COPY = [YOUR_ORIG_DICT mutableCopy];

Example: Add/Edit a key & object in it

[YOUR_MUTABLE_COPY setObject:someObject forKey:@"someKey"];

Upvotes: 0

Jim
Jim

Reputation: 73936

You'll have to create mutable copies. The enclosing array can't turn an object of one type into an object of another type; it's just a container. It doesn't store them "as" anything, mutable or non-mutable. It just holds onto pointers to them. The type of an object is determined by the way you instantiate it, not what it is contained by.

Upvotes: 2

Mundi
Mundi

Reputation: 80265

Yes, you will have to loop through the mutable collection and make all of its members mutable. I would advise you to you modify your FetchAllTheThings method to return a collection with members that are already mutable.

Upvotes: 4

D.C.
D.C.

Reputation: 15588

I think you are going to have to create a mutable copy. Nsdictionary has a mutableCopy method to make it easy, but you can imagine this would be inefficient if called a lot

Upvotes: 2

Related Questions