递归地遍历未知结构的NSDictionary [英] Recursively traverse NSDictionary of unknown structure
问题描述
有没有人做过一个未知结构的NSDictionary的递归有序遍历?我想采取任何NSDictionary并按层次顺序处理每个级别。
Has anyone done a recursive ordered traversal of an NSDictionary of unknown structure? I'd like to take any NSDictionary and process each level in hierarchical order.
1)这些数据来自经验证的JSON。是否可以说,从一个框架(如SBJSON(JSON框架)创建的NSDictionary只会导致嵌套字典,数组和任意叶子的组合?
1) This data is coming from validated JSON. Is it safe to say that the NSDictionary created from a framework such as SBJSON (JSON Framework) would only result in a combination of nested dictionaries, arrays, and arbitrary leafs?
2)如何使用适用于数组和字典的快速枚举完成通用遍历?使用下面的代码,一旦我到达数组中的字典,它停止遍历。但是,如果我继续在数组条件递归(检查数组中的字典),它将在下一次迭代 id value = [dict valueForKey:key];
与 - [__ NSCFDictionary长度]:无法识别的选择器发送到实例
SIGABRT。我不知道为什么这将是一个问题,因为我已经超过了一个顶级字典(其中发现了子级字典数组)。
2) How can a generic traversal be done using fast enumeration that works for both arrays and dictionaries? With the code below, once I get to a dictionary within an array, it stops traversing. However, if I continue the recursion in the array condition (to check for dictionaries within arrays), it barfs on the next iteration of id value = [dict valueForKey:key];
with a -[__NSCFDictionary length]: unrecognized selector sent to instance
SIGABRT. I don't know why this would be a problem, because I already got past that line with a top-level dictionary (where the array of sub-level dictionaries were found).
-(void)processParsedObject:(id)dict counter:(int)i parent:(NSString *)parent
{
for (id key in dict) {
id value = [dict valueForKey:key];
NSLog(@"%i : %@ : %@ -> %@", i, [value class], parent, key);
if ([value isKindOfClass:[NSDictionary class]])
{
i++;
NSDictionary* newDict = (NSDictionary*)value;
[self processParsedObject:newDict counter:i parent:(NSString*)key];
i--;
}
else if ([value isKindOfClass:[NSArray class]])
{
for (id obj in value) {
NSLog(@"Obj Type: %@", [obj class]);
}
}
}
}
感谢
推荐答案
我做了类似的事情,我将遍历一个来自一个Web服务的JSON结构化对象,一个可变的版本。
I've done something similar where I would traverse a JSON structured object coming from a web service and convert each element into a mutable version.
- (void)processParsedObject:(id)object
{
[self processParsedObject:object depth:0 parent:nil];
}
- (void)processParsedObject:(id)object depth:(int)depth parent:(id)parent
{
if ([object isKindOfClass:[NSDictionary class]])
{
for (NSString* key in [object allKeys])
{
id child = [object objectForKey:key];
[self processParsedObject:child depth:(depth + 1) parent:object];
}
}
else if ([object isKindOfClass:[NSArray class]])
{
for (id child in object)
{
[self processParsedObject:child depth:(depth + 1) parent:object];
}
}
else
{
// This object is not a container you might be interested in it's value
NSLog(@"Node: %@ depth: %d", [object description], depth);
}
}
这篇关于递归地遍历未知结构的NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!