Evgeniy Kleban Evgeniy Kleban - 2 months ago 4
iOS Question

Clear copied dictionary

Recently i created a post about clearing dictionary formed like key->value(NSArray).

I have 2 NSDictionary, first with data, second should contain all keys from first, but empty data for that key. Data will be added/removed later. This is how i create copy from main data dict (self.viewModel.releaseDict):

_releaseFormsDictCopy = [NSMutableDictionary dictionaryWithDictionary:self.viewModel.releaseDict];

When i checked, that objects (2 NSDictionaries) have different memory.

However, when i "clear" copy with method:


for(id key in self) {
NSMutableArray *arr = [self objectForKey:key];
[arr removeAllObjects];

It appears that it flush all data from both dictionaries, not only copy. How to prevent clearing first NSDictionary?


Your dictionaries may be different instances, but their contents are still the same instances - you have created a shallow (mutable) copy. From your description what you want is a deep copy, where the dictionaries are different instances and each of the arrays they contain as the values are also different instances.

Simple option is to deep copy only that level. Create an empty NSMutableDictionary and then enumerate self.viewModel.releaseDict and add each key with a mutableCopy of the value.

This will be a 'deep-ish' copy of the dictionary, containing a 'shallow' copy of each array it contains.