ios - NSMutableDictionary 删除键路径处的对象?

标签 ios objective-c nsmutabledictionary key-value-coding

我有一个分层的 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/

相关文章:

objective-c - 带有自定义单元格的 NSTableView

objective-c - 继续从 dequeueReusableCellWithIdentifier 获取 nil?

ios - 'NSMutableDictionary'没有可见的@interface声明选择器 'addObjects:forKey'

iphone - iOS 6中的"Do Not Disturb"功能如何实现?

ios - JSTileMap(.tmx) 与 Xcode SKTileMapNode

javascript - Titanium ios 选择器上的列未对齐

objective-c - 删除 View 、ARC、与 Objective C 和 Swift 的差异

ios - 自引用 NSMutableDictionary

objective-c - NSMutableDictionary 添加子项

ios - 将 Swift 3.0 的选择器转换为 2.2