PDA

View Full Version : NSMutableArray of NSMutableDictionaries. Updating a value




estupefactika
Jul 1, 2009, 10:49 AM
Hi, I have a NSMutableArray of NSMutableDictionaries. How Could I update the value for a key of my array?
My array is something like this:

(
{
name = "foo";
surname = "woo";
},
{
name = "foo2";
surname = "woo2";
}
)


I would like to update a value for key "name" for example:

for (int i=0; i<[feedArray count];i++) {
NSMutableDictionary *itemAtIndex = (NSMutableDictionary *)[feedArray objectAtIndex:i];
[itemAtIndex setValue:@"David" forKey:@"name"];

[feedArray insertObject:itemAtIndex atIndex:i];

}


But Im receiving the next error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '*** -[NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

It is any wrong? How Can I updated it? Thanks



PhoneyDeveloper
Jul 1, 2009, 11:43 AM
The runtime exception is telling you that you're trying to change a NSDictionary. IOW, what you think is a NSMutableDictionary is really a NSDictionary.

Look at the code for where you create the array of dictionaries.

Also, this line is wrong

[feedArray insertObject:itemAtIndex atIndex:i];
You should retrieve the dictionary at the desired index and update it. You don't have to insert it again.

estupefactika
Jul 1, 2009, 11:52 AM
The runtime exception is telling you that you're trying to change a NSDictionary. IOW, what you think is a NSMutableDictionary is really a NSDictionary.

Look at the code for where you create the array of dictionaries.

Also, this line is wrong

[feedArray insertObject:itemAtIndex atIndex:i];
You should retrieve the dictionary at the desired index and update it. You don't have to insert it again.

Ok. Thanks. Im creating my array in this way:

// save values to an item, then store that item into the array...
item = [[NSMutableDictionary alloc] init];
[item setObject:name forKey:@"name"];
[item setObject:surname forKey:@"surname"];
[feedArray addObject:[item copy]];
[item release];

Where feedArray is a NsMutableArray, item is a NsMutableDictionary and name and surname are NsMutableString. Is there any wrong there?

PhoneyDeveloper
Jul 1, 2009, 11:55 AM
Yes, copy returns an immutable copy. There's no reason to make a copy in this code that I can see. Just add item to the array.

[feedArray addObject:item];

If you must make a copy use

[item mutableCopy];

estupefactika
Jul 2, 2009, 04:26 AM
Yes. It works. Thanks