开发者

NSMutableDictionary, alloc, init and reiniting

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:[a开发者_开发知识库nArray objectAtIndex:i]];
} 

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

Thanks guy's.

Marcos.


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜