Reputation: 1497
I have a NSDictionary named tableData that contains keys @"A" - @"Z" and for every key the value contains an array with Patient objects.
I then create a NSMutableDictionary named filteredPatients and initialize it with the tableData dictionary.
In this example I try to remove all the Patient objects from the array where the key is @"A"
@property (nonatomic, strong) NSDictionary *tableData;
@property (nonatomic, strong) NSMutableDictionary *filteredPatients;
self.filteredPatients = [[NSMutableDictionary alloc]initWithDictionary:self.tableData];
NSMutableArray *patientArray = [self.filteredPatients objectForKey:@"A"];
int count = patientArray.count - 1;
for (int i = count; i >= 0; i--)
{
[patientArray removeObjectAtIndex:i];
}
In this case, the Patient Objects are getting removed correctly from filteredPatients array with key @"A", but the problem lay in the fact that the same Patient Objects are getting removed from tableData array with key @"A". My question is why are the Patient Objects being removed from the tableData dictionary as well? How do I prevent this?
I must be doing something wrong, but this puzzles me because if I try to simply remove the the key @"A" from filteredPatients, it works perfectly fine and only removes the key from the dictionary I want.
[self.filteredPatients removeObjectForKey:@"A"];
Upvotes: 1
Views: 926
Reputation: 44876
I think your problem is you're expecting deep copy behaviour but you haven't asked for a deep copy. The dictionaries are different objects, but the value for any given key in both dictionaries points to the same mutable array. You could use initWithDictionary:self.tableData copyItems:YES
instead, but you're going to need to think through what gets copied and what doesn't. I don't have enough information to help you with that.
Upvotes: 2