IOS - delete all entries containing the key on all NSDiction stored in the main NSDictionary

I have a main NSMutableDictionary that contains a collection of other NSMutableDictionary.

It goes like this:

NSMutableDictionary *subDict1 = [NSMutableDictionary dictionaryWithObjectsAndKeys: obj1, @"name", obj2, @"color", nil]; NSMutableDictionary *subDict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys: obj3, @"name", obj4, @"color", obj5, @"address", obj6, @"phone", obj7, @"color", obj8, @"parent", nil]; NSMutableDictionary *subDict3 = [NSMutableDictionary dictionaryWithObjectsAndKeys: obj0, @"name", obj9, @"parent", objA, @"site", objB, @"surname", objC, @"label", nil]; 

These auxiliary dictionaries may have a different number of entries, and the keys may be different. Some may have keys with the same name.

They are stored in the main dictionary, for example:

 NSMutableDictionary *mainDict = [NSMutableDictionary dictionaryWithObjectsAndKeys: subDict1, @"1", subDict3, @"3", subDict2, @"2", nil]; 

I want to delete all entries in all sub dictionaries with a certain key in one picture.

I know that I can iterate over dictionaries and sub dictionaries, but I also know that dictionaries have smart ways to do this using predicates and other things, but I don't see how to do this. I am trying to find this because the method that will be executed is a little more complicated and should do it as quickly as possible, and I'm not sure if the normal iteration with loops or something else will be fast enough ...

Any clues? thanks.

+4
source share
3 answers

Here's a recursive method that doesn't care how many levels are in the depth of the target key. (did not try) ...

 - (void)removeKey:(NSString *)keyToRemove fromDictionary:(NSMutableDictionary *)dictionary { NSArray *keys = [dictionary allKeys]; if ([keys containsObject:keyToRemove]) { [dictionary removeObjectForKey:keyToRemove]; } else { for (NSString *key in keys) { id value = [dictionary valueForKey:key]; if ([value isKindOfClass:[NSMutableDictionary self]]) { [self removeKey:keyToRemove fromDictionary:(NSMutableDictionary *)value]; } } } } 
+6
source

You just need to sort through all the subdirectories and manually delete the corresponding key-value pairs. You should not worry if it is fast enough at the moment. Rather, create a working implementation and test / measure it. If it is too slow, then you can tune it and devise ways to increase productivity. Premature optimization is a bad thing.

-1
source
 NSArray* keys = [NSArray arrayWithObjects:@"name", @"address", nil]; [dics removeObjectsForKeys:keys]; //Or sub dics 
-2
source

All Articles