简体   繁体   中英

Searching within subsubdictionaries of an array to return the parent dictionary (Objective C)

I have a structured array like the one below

 (
        {
        id = 0;
        name = "A";
        tables =         (
                        {
                comment = "";
                id = 0;
                name = "T1";
            },
                        {
                comment = "";
                id = 1;
                name = "T2";
            },
                        {
                comment = "";
                id = 4;
                name = "T3";
            }
        );
    },
        {
        id = 1;
        name = "B";
        tables =         (
                        {
                comment = "";
                id = 5;
                name = "T1";
            },
                        {
                comment = "";
                id = 6;
                name = "T2";
            }
        );
    }
) 

Given that I know the value of id key of one of the dictionaries (let's take id=6), how can I get its parent dictionary or to be more precise the value of name key (in this case B).

I've tried using predicate strings but the problem is that the parent dictionary has also a key named id, so I get the wrong results.

EDIT: id keys are unique (and it is also not necessary that ids of the elements in the first dictionary have lower intiger values than the ones in the dictionaries with higher indexes)

Try this, where array is your structured array

NSDictionary *parentDict=[[NSDictionary alloc]initWithDictionary:nil];
NSString *name=[[NSString alloc]init];
NSArray *table=[[NSArray alloc]initWithArray:nil];
for (NSDictionary * dict in array) {
    table=[dict objectForKey:@"tables"];
    for (NSDictionary *childDict in table) {
        if ([[childDict objectForKey:@"id"]isEqualToString:@"6"]) {
            //if your id value is int then use ==6 to check 
            parentDict=dict;
            name=[dict objectForKey:@"name"];
            return;                
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM