我有一个分层的 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
注意这要求路径的倒数第二个元素——tailContainer
是响应removeObjectForKey:
的东西,可能是另一个NSMutableDictionary
。如果不是,繁荣!
关于ios - NSMutableDictionary 删除键路径处的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15105709/