为嵌套的NSDictionary生成一个完整的键值编码路径列表?

时间:2013-05-10 23:27:18

标签: ios objective-c nsdictionary key-value-coding

我有NSDictionary包含键和值,有些值也是NSDictionary ...到任意(但合理)级别。

我想获得所有有效KVC路径的列表,例如给出:

{
    "foo" = "bar",
    "qux" = {
        "taco" = "delicious",
        "burrito" = "also delicious",
    }
}

我会得到:

[
    "foo",
    "qux",
    "qux.taco",
    "qux.burrito"
]

有一种简单的方法可以做到这一点吗?

2 个答案:

答案 0 :(得分:3)

您可以通过allKeys递归。显然,密钥是关键路径,然后如果值是NSDictionary,则可以递归和附加。

- (void) obtainKeyPaths:(id)val intoArray:(NSMutableArray*)arr withString:(NSString*)s {
    if ([val isKindOfClass:[NSDictionary class]]) {
        for (id aKey in [val allKeys]) {
            NSString* path = 
                (!s ? aKey : [NSString stringWithFormat:@"%@.%@", s, aKey]);
            [arr addObject: path];
            [self obtainKeyPaths: [val objectForKey:aKey] 
                       intoArray: arr 
                      withString: path];
        }
    }
}

以下是如何称呼它:

NSMutableArray* arr = [NSMutableArray array];
[self obtainKeyPaths:d intoArray:arr withString:nil];

之后,arr包含您的关键路径列表。

答案 1 :(得分:1)

这是我在马特回答后记下的一个Swift版本。

extension NSDictionary {
    func allKeyPaths() -> Set<String> {
        //Container for keypaths
        var keyPaths = Set<String>()
        //Recursive function
        func allKeyPaths(forDictionary dict: NSDictionary, previousKeyPath path: String?) {
            //Loop through the dictionary keys
            for key in dict.allKeys {
                //Define the new keyPath
                guard let key = key as? String else { continue }
                let keyPath = path != nil ? "\(path!).\(key)" : key
                //Recurse if the value for the key is another dictionary
                if let nextDict = dict[key] as? NSDictionary {
                    allKeyPaths(forDictionary: nextDict, previousKeyPath: keyPath)
                    continue
                }
                //End the recursion and append the keyPath
                keyPaths.insert(keyPath)
            }
        }
        allKeyPaths(forDictionary: self, previousKeyPath: nil)
        return keyPaths
    }
}