我有一个分层的 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 subarrayWithRangeNSRange){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/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |