2010-03-17 10 views
1

Dans le code suivant:NSMutableDictionary, alloc, init et reiniting

//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]]; 
} 

Pourquoi cet accident? Comment est la bonne façon d'effacer un nsmutabledict et d'assigner un nouveau dict?

Merci gars.

Marcos.

Répondre

3

Vous ne "reinit" pas d'objets - jamais. L'initialisation est destinée à être utilisée sur une nouvelle instance alloc ed et pourrait faire des suppositions qui ne sont pas vraies après l'initialisation est terminée. Dans le cas de NSMutableDictionary, vous pouvez utiliser setDictionary: pour remplacer complètement le contenu du dictionnaire par un nouveau dictionnaire ou addEntriesFromDictionary: pour ajouter les entrées d'un autre dictionnaire (sans se débarrasser des entrées actuelles sauf s'il y a des conflits). Plus généralement, vous pouvez simplement libérer ce dictionnaire et créer un mutableCopy du dictionnaire dans le tableau.

+0

Okay! C'est une bonne explication! –

+0

@Marcos: Alors vous devriez * accepter * la réponse de @ Chuck. C'est la façon d'honorer les bonnes réponses à vos questions. –

2

Si vous utilisez un dictionnaire autoreleased, votre code sera beaucoup plus simple:

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

... use of anMutableDict ... 

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

Mais je ne vois pas le point de cette boucle que vous avez à la fin là.

+0

Désolé, c'est un code incomplet. Dans la boucle je charge le dict puis l'utilise. –

+0

@Marcos, alors l'exemple que j'ai ci-dessus devrait fonctionner pour vous. –

1

Ce n'est pas comme cela que vous utilisez init/alloc. Au lieu de cela, essayez:

//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]]; 
}