How to copy NSMutableDictionary

Discussion in 'iOS Programming' started by diyora, Oct 13, 2008.

  1. diyora macrumors newbie

    Joined:
    Jul 21, 2008
    #1
    Hello all,
    I have one mutableDictionary in which mutableArray and other object.
    I copy this original dictionary in new dictionary using dictionaryWithditionary.
    now when i reomve object from newdictionary then it not remove from originaldictionary.It working properly.
    But it create problem for mutableArray. When i remove one object from mutalbleArray which is in newdictionary then it also remove from original dictionary.

    Thank you.
     
  2. Jahz macrumors newbie

    Joined:
    Nov 15, 2006
    #2
    Of course this happens... the arrays in both dictionaries are the same object. First off, the constructor you are using does not mention the word "copy", so it has no obligation to preform any copy as defined in NSCopying. However, even if it did use [NSDictionary copy], it would now be a deep copy. Deep copy includes copying all the child values for every object. Shallow copy (the default for [copy]) just copies pointers and primitive values.

    Remember that you can't put an NSArray into a dictionary. You only put an NSArray* (pointer) into a dictionary. When you use [dictionaryWithDictionary:] or [initWithDictionary:], the new dictionary has copies of all of the values in the original array, including COPIES OF THE POINTERS. Both pointers still refer to the same array object, so operating on the array* in one of the dictionaries will will modify the "array" in both dictionaries.

    Deep copying is a very delicate and frequently specific operation. It can be slow and can even cause recursive looping, so its never the default!

    Check out http://developer.apple.com/document...ions.html#//apple_ref/doc/uid/20001149-102844

    Specifically, try using:
    Code:
    NSMutableDictionary* newDict = (NSMutableDictionary*) CFPropertyListCreateDeepCopy (
       kCFAllocatorDefault,
       yourDictonaryPointer,
       kCFPropertyListMutableContainersAndLeaves
    );
    
    // you own new object
    // do stuff
    
    [newDict release];
    
     
  3. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #3
    A dictionary is a container. When you make a copy using dictionaryWithDictionary you get two dictionary with the exact same contents. So if you modify an object that's in one dictionary it will modify the same object that's in the other dictionary.

    You can use

    Code:
    - (id)initWithDictionary:(NSDictionary *)otherDictionary copyItems:(BOOL)flag;
    
    to make a deep copy.
     

Share This Page