Home > OS >  Checking if key exist in NSDictionary at first and second level
Checking if key exist in NSDictionary at first and second level

Time:10-13

I have two different dataset but need to check if dictionary has emp_id or not in the two given dictionary. I could not know how to handle the second level dictionary check in the given dataset

NSDictionary *data = nil;

NSDictionary *data = @{@"emp_id" : @"123456"};

NSDictionary *data = @{@"emp_id" : @{@"emp_id" : @"123456"}}; 

BOOL isEmpExist = [data containsObjectForKey :@"emp_id"]; // works for the first example

BOOL isSecondLevelExist = [data containsObjectForKey :@"emp_id"] 
                           containsObjectForKey@"emp_id"]; // crashes if we have one level data

if (isEmpExist) {
    // yes found
}else {
    // not found!
}

CodePudding user response:

NSDictionary *data1 = @{@"emp_id" : @"123456"};

NSDictionary *data2 = @{@"emp_id" : @{@"emp_id" : @"123456"}}; 

(I've renamed these two variables from your question so that I can refer to each one directly.)

Notice that in data1, the value of emp_id is an NSString. In data2, the value of the outer emp_id is an NSDictionary. So there are four possibilities:

  1. There is no outer emp_id (thus no inner emp_id).
  2. There is an outer emp_id, but its value is not an NSDictionary (thus no inner emp_id).
  3. There is an outer emp_id, and its value is an NSDictionary, but that dictionary doesn't contain emp_id.
  4. There is an outer emp_id, and its value is an NSDictionary, and that dictionary contains an emp_id.

I think it's easier to handle the cases in a slightly different order in code:

id outerValue = data[@"emp_id"];
if (outerValue == nil) {
    // case 1: outer emp_id does not exist, inner emp_id cannot exist
} else if ([outerValue isKindOfClass:NSDictionary.self]) {
    id innerValue = [outerValue objectForKey:@"emp_id"];
    if (innerValue == nil) {
        // case 3: outer emp_id exists, inner emp_id does not
    } else {
        // case 4: outer emp_id exists, inner emp_id also exists
    }
} else {
    // case 2: outer emp_id exists, inner emp_id cannot exist
}
  • Related