有没有人对未知结构的 NSDictionary 进行过递归有序遍历?我想采用任何 NSDictionary 并按层次顺序处理每个级别。
1) 此数据来自经过验证的 JSON。可以肯定地说,从 SBJSON(JSON 框架)等框架创建的 NSDictionary 只会导致嵌套字典、数组和任意叶子的组合吗?
2) 如何使用适用于数组和字典的快速枚举来完成通用遍历?使用下面的代码,一旦我到达数组中的字典,它就会停止遍历。但是,如果我在数组条件中继续递归(检查数组中的字典),它会在 id value = [dict valueForKey:key];
的下一次迭代中使用 - [__NSCFDictionary 长度]:发送到实例的无法识别的选择器
SIGABRT。我不知道为什么这会成为一个问题,因为我已经通过顶级字典(找到子级字典数组的地方)过了那条线。
-(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);
}
}
关于iphone - 递归遍历未知结构的NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9186170/