3

我有一个NSDictionary包含键和值的值,并且某些值也将NSDictionary...达到任意(但合理)的水平。

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

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

我会得到:

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

有没有一种简单的方法可以做到这一点已经存在?

4

2 回答 2

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包含您的关键路径列表。

于 2013-05-11T00:05:06.583 回答
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
    }
}
于 2016-02-23T14:44:16.147 回答