NSDictionary 또는 NSMutableDictionary에 키가 포함되어 있는지 확인하는 방법
딕트에 열쇠가 있는지 확인해봐야겠어
objectForKey키가 존재하지 않으면 0이 반환됩니다.
if ([[dictionary allKeys] containsObject:key]) {
// contains key
/* Don't use this solution. Look for more details in comments. */
}
또는
if ([dictionary objectForKey:key]) {
// contains object
}
Objective-C 및 Clang의 최신 버전은 다음과 같은 최신 구문을 사용합니다.
if (myDictionary[myKey]) {
}
nil Objective-C 객체가 아닌 객체만 사전(또는 배열)에 저장할 수 있으므로 0과 동일한지 확인할 필요가 없습니다.Objective-C 오브젝트는 모두 truthy 값입니다.심지어.@NO,@0,그리고.[NSNull null]사실로 평가하다
편집: 이제 Swift가 인기입니다.
Swift의 경우 다음과 같은 작업을 시도합니다.
if let value = myDictionary[myKey] {
}
이 구문은 myKey가 dict에 있고, dict에 있는 경우 값이 값 변수에 저장되는 경우에만 if 블록을 실행합니다.이 값은 0과 같은 falsey 값에도 적용됩니다.
if ([mydict objectForKey:@"mykey"]) {
// key exists.
}
else
{
// ...
}
JSON 사전을 사용하는 경우:
#define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]
if( isNull( dict[@"my_key"] ) )
{
// do stuff
}
당신이 두 번이나 obj를 요구해도 나는 Fernandes의 대답이 좋다.
이것 또한 (대부분 마틴의 A와 동일)할 것입니다.
id obj;
if ((obj=[dict objectForKey:@"blah"])) {
// use obj
} else {
// Do something else like creating the obj and add the kv pair to the dict
}
Martin과 이 답변은 모두 iPad2 iOS 5.0.1 9A405에서 작동합니다.
디버깅에 시간을 조금 낭비한 매우 귀찮은 gotcha가 있습니다.자동완성이라는 메시지가 뜨면 사용법을 시도해 볼 수 있습니다.doesContain효과가 있는 것 같아요
제외하고,doesContain는 에서 사용되는 해시 비교 대신 ID 비교를 사용합니다.objectForKey따라서 문자열 키가 있는 사전이 있으면 NO가 반환됩니다.doesContain.
NSMutableDictionary* keysByName = [[NSMutableDictionary alloc] init];
keysByName[@"fred"] = @1;
NSString* test = @"fred";
if ([keysByName objectForKey:test] != nil)
NSLog(@"\nit works for key lookups"); // OK
else
NSLog(@"\nsod it");
if (keysByName[test] != nil)
NSLog(@"\nit works for key lookups using indexed syntax"); // OK
else
NSLog(@"\nsod it");
if ([keysByName doesContain:@"fred"])
NSLog(@"\n doesContain works literally");
else
NSLog(@"\nsod it"); // this one fails because of id comparison used by doesContain
Swift를 사용하면 다음과 같습니다.
if myDic[KEY] != nil {
// key exists
}
네. 이런 종류의 오류는 매우 흔하고 앱 크래시로 이어집니다.그래서 저는 다음과 같이 각 프로젝트에 NSDictionary를 추가합니다.
//.h 파일코드:
@interface NSDictionary (AppDictionary)
- (id)objectForKeyNotNull : (id)key;
@end
//.m 파일코드는 다음과 같습니다.
#import "NSDictionary+WKDictionary.h"
@implementation NSDictionary (WKDictionary)
- (id)objectForKeyNotNull:(id)key {
id object = [self objectForKey:key];
if (object == [NSNull null])
return nil;
return object;
}
@end
코드에서는 다음과 같이 사용할 수 있습니다.
NSStrting *testString = [dict objectForKeyNotNull:@"blah"];
NSDictionary에서 키의 존재를 확인하는 경우:
if([dictionary objectForKey:@"Replace your key here"] != nil)
NSLog(@"Key Exists");
else
NSLog(@"Key not Exists");
0은 Foundation 데이터 구조에 저장할 수 없기 때문입니다.NSNull때로는 의 상징이 되기도 한다.nil.왜냐면NSNull싱글톤 오브젝트입니다.NSNull는 직접 포인터 비교를 사용하여 사전에 저장된 값입니다.
if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }
신속한 4.2를 위한 솔루션
따라서 사전에 키가 포함되어 있는지 여부를 묻는 질문에만 답하려면 다음과 같이 질문합니다.
let keyExists = dict[key] != nil
값을 원하는 경우 사전에 키가 포함되어 있는 경우 다음과 같이 입력합니다.
let val = dict[key]!
그러나 일반적으로 키가 포함되어 있지 않은 경우에는 키를 가져와 사용하고 싶은 경우에만 다음과 같은 것을 사용합니다.if let:
if let val = dict[key] {
// now val is not nil and the Optional has been unwrapped, so use it
}
조회 결과를 temp 변수에 저장하고 temp 변수가 0인지 테스트한 후 사용할 것을 권장합니다.이렇게 하면 동일한 개체를 두 번 검색하지 않습니다.
id obj = [dict objectForKey:@"blah"];
if (obj) {
// use obj
} else {
// Do something else
}
objectForKey가 하는데, 때objectForKey늘러블 사전에서는 앱이 크래쉬가 되어 버리기 때문에 아래와 같이 수정했습니다.
- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;
if (dictionary && (object != [NSNull null])) {
self.name = [dictionary objectForKey:@"name"];
self.age = [dictionary objectForKey:@"age"];
}
return self;
}
if ([MyDictionary objectForKey:MyKey]) {
// "Key Exist"
}
if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
//do something if doesn't exist
}
중첩된 사전 구조에 대한 것입니다.
언급URL : https://stackoverflow.com/questions/2784648/how-to-check-if-an-nsdictionary-or-nsmutabledictionary-contains-a-key
'codememo' 카테고리의 다른 글
| 공백이 없는 여러 개의 탭 문자("nbsp") 대신 탭 문자를 선택하십시오. (0) | 2023.04.18 |
|---|---|
| Zsh에는 .bash_profile과 같은 것이 있습니까? (0) | 2023.04.18 |
| SQL-Server에 퍼센트 값을 저장하는 가장 좋은 방법은 무엇입니까? (0) | 2023.04.18 |
| 셀에서 복사할 때 따옴표 생략 (0) | 2023.04.18 |
| bash에 함수가 존재하는지 확인합니다. (0) | 2023.04.18 |