Old*_*her 13 iphone recursion cocoa-touch json ios
有没有人对未知结构的NSDictionary进行递归有序遍历?我想采用任何NSDictionary并按层次顺序处理每个级别.
1)此数据来自经过验证的JSON.可以肯定地说,从诸如SBJSON(JSON框架)之类的框架创建的NSDictionary只会导致嵌套字典,数组和任意叶子的组合?
2)如何使用适用于数组和字典的快速枚举来完成泛型遍历?使用下面的代码,一旦我到达数组中的字典,它就会停止遍历.但是,如果我继续数组条件中的递归(以检查数组中的字典),它会在下一次id value = [dict valueForKey:key];使用-[__NSCFDictionary length]: unrecognized selector sent to instanceSIGABRT的迭代时进行barfs.我不知道为什么这会是一个问题,因为我已经超过了顶级字典的那一行(其中找到了子级字典的数组).
-(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]);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢
Joe*_*ets 32
我做了类似的事情,我将遍历来自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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6817 次 |
| 最近记录: |