bestsource

NSDictionary에 키가 있는지 확인합니다.

bestsource 2023. 8. 27. 09:44
반응형

NSDictionary에 키가 있는지 확인합니다.

이것이 존재하는지 어떻게 확인할 수 있습니까?:

[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"]

저는 이 키가 존재하는지 알고 싶습니다.내가 어떻게 그럴 수 있을까?

정말 감사합니다 :)

편집: dataArray에 개체가 있습니다.그리고 이 물체들은 NS 사전입니다.

라고 추측하건대[dataArray objectAtIndex:indexPathSet.row]를 반환하는 것입니다. 이 경우 단순히 의 결과를 확인할 수 있습니다.valueForKey그에 반대하여nil.

예:

if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // The key existed...

}
else {
    // No joy...

}

그래서 당신이 이미 답을 선택했다는 것을 알지만, 저는 이것이 오히려 카테고리로서 유용하다는 것을 알았습니다.NSDictionary이 시점에서 다양한 답변을 통해 효율성을 실현할 수 있습니다.음... 6/1...

- (BOOL)containsKey: (NSString *)key {
     BOOL retVal = 0;
     NSArray *allKeys = [self allKeys];
     retVal = [allKeys containsObject:key];
     return retVal;
}

0인지 확인합니다.

if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // SetEntries exists in this dict
} else {
    // No SetEntries in this dict
}

이것은 또한 다음 구문을 사용하여 목표-C 리터럴을 사용하여 작동합니다.

NSDictionary *dict = @{ @"key1" : @"value1", @"key2" : @"value2" };
if (dict[@"key2"])
NSLog(@"Exists");
else
NSLog(@"Does not exist");

사용해 보십시오.

if ([dict objectForKey:@"bla"]) {
   // use obj
} else {
   // Do something else like create the object
}

이 기능은 동일하지만 코드 수가 적습니다.

if (dataArray[indexPathSet.row][@"SetEntries"] != nil) { /* the key exists */        } 
else                                                   { /* the key doesn't exist */ }
if ((NSNull *)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // SetEntries exists in this dict
} else {
    // No SetEntries in this dict
}

정답입니다.

사전에 값이 있는지 확인합니다.[dicallKeys]를 선호합니다.확인하려면 count > 0.

사용(unsigned long)옵션:

if ( (unsigned long)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] ) {
    // Key exist;
}else{
    // Key not exist;
};

언급URL : https://stackoverflow.com/questions/4635106/check-key-exists-in-nsdictionary

반응형