是否有人对未知结构的NSDictionary进行了递归有序遍历?我想学习任何NSDictionary,并按层次结构顺序处理每个级别。
1)此数据来自经过验证的JSON。可以肯定地说,从诸如SBJSON(JSON框架)之类的框架创建的NSDictionary仅会导致嵌套字典,数组和任意叶的组合吗?
2)如何使用适用于数组和字典的快速枚举完成泛型遍历?使用下面的代码,一旦我到达数组中的字典,它将停止遍历。但是,如果我继续在排列条件(以检查阵列内的字典)递归,它barfs上的下一个迭代id value = [dict valueForKey:key];用-[__NSCFDictionary length]: unrecognized selector sent to instanceSIGABRT。我不知道为什么会出现问题,因为我已经越过了顶层字典(找到了次级字典数组)。
id value = [dict valueForKey:key];
-[__NSCFDictionary length]: unrecognized selector sent to instance
-(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结构化对象并将每个元素转换为可变版本。
- (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); } }