我有兩個不同的資料集,但需要檢查字典在兩個給定字典中是否有 emp_id。我不知道如何處理給定資料集中的二級字典檢查
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!
}
uj5u.com熱心網友回復:
NSDictionary *data1 = @{@"emp_id" : @"123456"};
NSDictionary *data2 = @{@"emp_id" : @{@"emp_id" : @"123456"}};
(我已從您的問題中重命名這兩個變數,以便我可以直接參考每個變數。)
請注意,在 中data1, 的值emp_id是NSString。在data2中,外部的值emp_id是一個NSDictionary。所以有四種可能:
- 沒有外部
emp_id(因此沒有內部emp_id)。 - 有一個外部
emp_id,但它的值不是一個NSDictionary(因此沒有內部emp_id)。 - 有一個 external
emp_id,它的值為 anNSDictionary,但該字典不包含emp_id。 - 有一個外部的
emp_id,它的值是一個NSDictionary,并且該字典包含一個emp_id。
我認為在代碼中以稍微不同的順序處理這些案例會更容易:
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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/514418.html
標籤:目标-c
