0

First of all I found something similar: deep mutable copy of a NSMutableDictionary but it didn't solve my problem.

I have a NSMutableDictionary as a template.

NSMutableDictionary *mutableDictionaryTemplate = [NSMutableDictionary dictionaryWithObjectsAndKeys: @"obj1, @"key1",@"obj2, @"key2",nil];

Now I would like to copy this dictionary, then change some parts and later save it in a NSMutable Array.

NSMutableArray *savedIterations = [NSMutableArray new];

//some loop that normally would change the objects added
int i=0;
for (i < 5){

    NSMutableDictionary *copiedDictionary = [mutableDictionaryTemplate copy];
    [copiedDictionary setObject:@"obj3" forKey:@"key3"];
    [savedIterations addObject:copiedDictionary];

    i++;
}

My problem is that once I copy the NSMutableDictionary "mutableDictionaryTemplate" it no longer is mutable. But I need to copy it because otherwise I will have the same NSMutableDictionary at every index of my NSMutableArray "savedIterations" (at least I think so). I tried mutable copy as well but there I change the "mutableDictionaryTemplate" when I change "copiedDictionary". I think I have something messed up with what I have to copy and what not and how to copy it correctly. It would be great if someone could point me into the right direction.

Community
  • 1
  • 1
Marty
  • 131
  • 1
  • 10

1 Answers1

1

You could try this:

    NSMutableDictionary *destinationDictionary = (NSMutableDictionary *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (__bridge CFPropertyListRef)(sourceDictionary), kCFPropertyListMutableContainers));
Jonah
  • 4,810
  • 14
  • 63
  • 76