Recursively traverse NSDictionary of unknown structure

前端 未结 2 1696
Happy的楠姐
Happy的楠姐 2020-12-07 23:47

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.

2条回答
  •  一个人的身影
    2020-12-08 00:17

    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);
        }
    }
    

提交回复
热议问题