1

I'll try to be as much clear as possible:

  1. I create 2 MutableDictionary
  2. I add to both of them the same NSMutableArray object:

    [self.myList setObject:tempC forKey:keyV];
    
    [self.listFiltered setObject:tempC forKey:keyV];
    
  3. In other part of the code, I want to empty one, so I do:

    [self.listFiltered objectForKey:keyV] removeAllObjects];
    

The problem is that the objects are being removed in BOTH mutableDictionaries!

JeremyP
  • 84,577
  • 15
  • 123
  • 161
Antonio MG
  • 20,382
  • 3
  • 43
  • 62

3 Answers3

2

Both objects are same... you only provide a pointer to that mutablearray to both the dictionary so when you delete in one the other also gets deleted .. what you need is to store copy of that array into your dictionary... hoping this helps.

you can add the array like this..(Seems to me you want a deep copy)

NSMutableArray *newArrayOne = [[NSMutableArray alloc] initWithArray:tempC copyItems:YES];
[self.myList setObject:newArrayOne   forKey:keyV];
[newArrayOne release];

NSMutableArray *newArrayTwo = [[NSMutableArray alloc] initWithArray:tempC copyItems:YES];
[self.listFiltered setObject:newArrayTwo   forKey:keyV];
[newArrayTwo  release];

this way two different objects are stored in there.. this is not the most optimized code.. it is just to make you understand what actually is happening behind the scenes.

freespace
  • 16,529
  • 4
  • 36
  • 58
Ankit Srivastava
  • 12,347
  • 11
  • 63
  • 115
2

You need to copy the array to the other dictionary. See here on how you can go about this.

Community
  • 1
  • 1
Madhu
  • 2,429
  • 16
  • 31
2

The same NSNSMutableArray is added to both dictionaries. It doesn't matter whether you access it through one dictionary or the other, you end up manipulating the same NSMutableArray instance.

To fix this, you need store different NSMutableArray instances in each dictionary. The easiest way to do this is through [NSMutableArray copy], which will do a shallow copy.

Lastly, naming dictionaries with names ending in list is a bad practice.

freespace
  • 16,529
  • 4
  • 36
  • 58
  • Working, thanks! Btw, how would you recommend me to name them? – Antonio MG Mar 19 '12 at 09:51
  • `myDictionary` and `dictionaryFiltered` comes to mind. If dictionary is too long for you liking, `dict` is an acceptable contraction, and the same length as `list`. – freespace Mar 19 '12 at 09:53