views:

515

answers:

3

In the following code:

//anArray is a Array of Dictionary with 5 objs. 

//here we init with the first
NSMutableDictionary *anMutableDict = [[NSMutableDictionary alloc] initWithDictionary:[anArray objectAtIndex:0]];

... use of anMutableDict ...
//then want to clear the MutableDict and assign the other dicts that was in the array of dicts

for (int i=1;i<5;i++) {
    [anMutableDict removeAllObjects];
    [anMutableDict initWithDictionary:[anArray objectAtIndex:i]];
} 

Why this crash? How is the right way to clear an nsmutabledict and the assign a new dict?

Thanks guy's.

Marcos.

A: 

If you use an autoreleased dictionary, your code will be a lot simpler:

NSMutableDictionary *anMutableDict = [NSMutableDictionary dictionaryWithDictionary:[anArray objectAtIndex:0]];

... use of anMutableDict ...

for (int i=1; i<5; i++)
{
    anMutableDict = [NSMutableDictionary dictionaryWithDictionary:[anArray objectAtIndex:i]];
} 

But I don't see the point of that loop you have at the end there.

Carl Norum
ow, sorry, it's a incomplete code. In the loop i load the dict an then use it.
Marcos Issler
@Marcos, then the example I have above should work for you.
Carl Norum
+1  A: 

This isn't how you use init/alloc. Instead, try:

//anArray is a Array of Dictionary with 5 objs. 

//here we init with the first
NSMutableDictionary *anMutableDict = [[NSMutableDictionary alloc] initWithDictionary:[anArray objectAtIndex:0]];

... use of anMutableDict ...
//then want to clear the MutableDict and assign the other dicts that was in the array of dicts

for (int i=1;i<5;i++) {
    [anMutableDict removeAllObjects];
    [anMutableDict addEntriesFromDictionary:[anArray objectAtIndex:i]];
} 
Steven Canfield
+1  A: 

You do not "reinit" objects — ever. Initialization is meant to be used on a newly alloced instance and might make assumptions that aren't true after initialization is complete. In the case of NSMutableDictionary, you can use setDictionary: to completely replace the contents of the dictionary with a new dictionary or addEntriesFromDictionary: to add the entries from another dictionary (without getting rid of the current entries unless there are conflicts).

More generally, you could just release that dictionary and make a mutableCopy of the dictionary in the array.

Chuck
Okay! This is a good explanation!
Marcos Issler
@Marcos: Then you should *accept* @Chuck’s answer. That’s the SO-way of honoring good answers to your questions.
Nikolai Ruhe