NSMutableDictionary在关键路径中删除对象?

我有一个分层的NSMutableDictionary对象,我希望能够删除层次结构中更深层次的字典。 有没有一种快速简便的方法来做到这一点,例如,类似removeObjectAtKeyPath的方法? 似乎无法找到一个。

谢谢!

什么都没有内置,但你的基本类别方法会做得很好:

 @implementation NSMutableDictionary (WSSNestedMutableDictionaries) - (void)WSSRemoveObjectForKeyPath: (NSString *)keyPath { // Separate the key path NSArray * keyPathElements = [keyPath componentsSeparatedByString:@"."]; // Drop the last element and rejoin the path NSUInteger numElements = [keyPathElements count]; NSString * keyPathHead = [[keyPathElements subarrayWithRange:(NSRange){0, numElements - 1}] componentsJoinedByString:@"."]; // Get the mutable dictionary represented by the path minus that last element NSMutableDictionary * tailContainer = [self valueForKeyPath:keyPathHead]; // Remove the object represented by the last element [tailContainer removeObjectForKey:[keyPathElements lastObject]]; } @end 

NB这需要路径的tailContainer第二个元素 – tailContainer是响应removeObjectForKey:东西,可能是另一个NSMutableDictionary 。 如果不是,繁荣!

您可以创建一个类别:

这是最多1级:

 #import "NSMutableDictionary+RemoveAtKeyPath.h" @implementation NSMutableDictionary (RemoveAtKeyPath) -(void)removeObjectAtKeyPath:(NSString *)keyPath{ NSArray *paths=[keyPath componentsSeparatedByString:@"."]; [[self objectForKey:paths[0]] removeObjectForKey:paths[1]]; } @end 

它被称为:

 NSMutableDictionary *adict=[[NSMutableDictionary alloc]initWithDictionary:@{@"key1" : @"obj1", @"key11":@"obj11"}]; NSMutableDictionary *bdict=[[NSMutableDictionary alloc]initWithDictionary:@{@"key2" : adict}]; NSLog(@"%@",bdict); NSLog(@"%@",[bdict valueForKeyPath:@"key2.key1"]); [bdict removeObjectAtKeyPath:@"key2.key1"]; NSLog(@"After category : %@",bdict); 

为了处理不包含句点的键路径(即实际键的键路径),Josh的答案略有改进:

 - (void)removeObjectAtKeyPath:(NSString *)keyPath { NSArray *keyPathElements = [keyPath componentsSeparatedByString:@"."]; NSUInteger numElements = [keyPathElements count]; if (numElements == 1) { [self removeObjectForKey:keyPath]; } else { NSString *keyPathHead = [[keyPathElements subarrayWithRange:(NSRange){0, numElements - 1}] componentsJoinedByString:@"."]; NSMutableDictionary *tailContainer = [self valueForKeyPath:keyPathHead]; [tailContainer removeObjectForKey:[keyPathElements lastObject]]; } } 

我知道这是一篇较旧的post,但是我需要在Swift 2.0中找到相同的解决方案,无法找到一个简单的答案我想出了这个解决方案:

 public extension NSMutableDictionary { public func removeObjectAtKeyPath(keyPath:String) { let elements = keyPath.componentsSeparatedByString(".") let head = elements.first! if elements.count > 1 { let tail = elements[1...elements.count-1].joinWithSeparator(".") if let d = valueForKeyPath(head) as? NSMutableDictionary { d.removeObjectAtKeyPath(tail) } }else{ removeObjectForKey(keyPath) } } } 

我已经使用递归向NSMutableDictionary添加了一个扩展来逐步通过keyPath