本文介绍了为嵌套的 NSDictionary 生成完整的键值编码路径列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含键和值的 NSDictionary
,有些值也将是 NSDictionary
s... 到任意(但合理)的级别.
我想获得所有有效 KVC 路径的列表,例如给定:
{"foo" = "bar",qux"= {炸玉米饼"=美味","burrito" = "也很好吃",}}
我会得到:
["富","qux","qux.taco",qux.burrito"]是否有一种已经存在的简单方法可以做到这一点?
解决方案
您可以通过 allKeys
递归.一个键显然是一个键路径,然后如果值是一个 NSDictionary 你可以递归和追加.
- (void)获取KeyPaths:(id)val intoArray:(NSMutableArray*)arr withString:(NSString*)s {如果 ([val isKindOfClass:[NSDictionary 类]]) {for (id aKey in [val allKeys]) {NSString* 路径 =(!s ? aKey : [NSString stringWithFormat:@"%@.%@", s, aKey]);[arr addObject: 路径];[自获取KeyPaths:[val objectForKey:aKey]进入数组: arrwithString: 路径];}}}
这里是如何调用它:
NSMutableArray* arr = [NSMutableArray 数组];[自获取KeyPaths:d intoArray:arr withString:nil];
之后,arr
包含您的关键路径列表.
I have an NSDictionary
that contains keys and values, and some values will also be NSDictionary
s... to an arbitrary (but reasonable) level.
I would like to get a list of all valid KVC paths, e.g. given:
{
"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
. A key is a key path, obviously, and then if the value is an NSDictionary you can recurse and append.
- (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.
这篇关于为嵌套的 NSDictionary 生成完整的键值编码路径列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!