how to iterate nested dictionaries in objective-c iphone sdk

前端 未结 5 748
天命终不由人
天命终不由人 2021-01-13 11:35

Hi I have a json string converted unsing the JSON framework into a dictionary and I need to extract its content. How could I iterate to the nested dictionaries? I have alrea

5条回答
  •  一生所求
    2021-01-13 11:55

    The header of the category:

    #import 
    
    @interface NSDictionary(Find)
    
    -(id) findflat:(NSString*)keyToFind;
    
    @end
    

    The body:

    #import "NSDictionary+Find.h"
    
    @implementation NSDictionary(Find)
    
    -(id) findflat:(NSString*)keyToFind{
    
        if([self objectForKey:keyToFind])
            return self[keyToFind];
    
        for(id key in self)
            if([[self objectForKey:key] isKindOfClass:[NSDictionary class]])
                return [[self objectForKey:key] findflat:keyToFind];
    
    
        return nil;
    }
    
    @end
    

    Usage/Validation:

    - (void)testExample {
    // This is an example of a functional test case.
    // Use XCTAssert and related functions to verify your tests produce the correct results.
    
    NSDictionary *dic = @{};
    XCTAssertNil([dic findflat:@"url"]);
    
    dic = @{@"url":@"http://"};
    XCTAssertEqual([dic findflat:@"url"],@"http://");
    
    dic = @{@"other":@4};
    XCTAssertNil([dic findflat:@"url"]);
    
    dic = @{@"other":@4,@"url":@"http://"};
    XCTAssertEqual([dic findflat:@"url"],@"http://");
    
    dic = @{@"other":@4,@"sd":@"sdf"};
    XCTAssertNil([dic findflat:@"url"]);
    
    dic = @{@"other":@4,@"dic":@{@"url":@"http://"}};
    XCTAssertEqual([dic findflat:@"url"],@"http://");
    
    dic = @{@"other":@4,@"dic":@{@"sd":@2,@"url":@"http://"}};
    XCTAssertEqual([dic findflat:@"url"],@"http://");
    
    dic = @{@"other":@4,@"dic":@{}};
    XCTAssertNil([dic findflat:@"url"]);
    
    dic = @{@"other":@4,@"dic":@{@"dic":@{@"sd":@2,@"url":@"http://"}}};
    XCTAssertEqual([dic findflat:@"url"],@"http://");
    

    }

提交回复
热议问题