iOS - deleting all entries containing a key on all NSDictionaries stored inside a main NSDictionary
cocoa-touch, ios, ipad, iphone
Solution
Here's a recursive method that doesn't care how many levels deep the target key is. (haven't tried it) ...
- (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];
}
}
}
}
Problem
I have a main NSMutableDictionary that contains a collection of others NSMutableDictionary. The thing 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 sub dictionaries may have different number of entries and the keys may vary. Some may have keys with the same name. They are stored in a main dictionary like this: ``` NSMutableDictionary *mainDict = [NSMutableDictionary dictionaryWithObjectsAndKeys: subDict1, @"1", subDict3, @"3", subDict2, @"2", nil]; ``` I want at one shot, remove all entries in all sub dictionaries that have a specific key. I know I can iterate thru the dictionaries and sub dictionaries, but I also know that Dictionaries have smart ways to do that using predicates and other stuff, but I am not seeing how. I am trying to find that because the method this will run is a little bit tricky and have to do it as fast as possible and I am not sure if normal iteration with loops or whatever will be fast enough... Any clues? thanks.