[英]Generate a complete list of key-value coding paths for nested NSDictionary's?
I have an NSDictionary
that contains keys and values, and some values will also be NSDictionary
s... to an arbitrary (but reasonable) level. 我有一个包含键和值的
NSDictionary
,并且一些值也将是NSDictionary
s ...到任意(但合理)级别。
I would like to get a list of all valid KVC paths, eg given: 我想获得所有有效KVC路径的列表,例如:
{
"foo" = "bar",
"qux" = {
"taco" = "delicious",
"burrito" = "also delicious",
}
}
I would get: 我会得到:
[
"foo",
"qux",
"qux.taco",
"qux.burrito"
]
Is there a simple way to do this that already exists? 是否有一种简单的方法可以做到这一点已经存在?
You could recurse through allKeys
. 你可以通过
allKeys
来allKeys
。 A key is a key path, obviously, and then if the value is an NSDictionary you can recurse and append. 显然,键是键路径,然后如果值是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];
}
}
}
And here is how to call it: 以下是如何称呼它:
NSMutableArray* arr = [NSMutableArray array];
[self obtainKeyPaths:d intoArray:arr withString:nil];
Afterwards, arr
contains your list of key paths. 之后,
arr
包含您的关键路径列表。
Here is a Swift version I wrote after taking note from Matt's answer. 这是我在马特回答后记下的一个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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.