【Objective-C】NSDictionary キーの存在チェック
残念ながらJavaにある Map#containsKey のようなメソッドはない模様。。。
なので以下の方法で。
- NSArray containsObject: を利用する方法
- NSDictionary objectForKey: を利用する方法
NSArray *keys = @[@"key1",@"key2",@"key3",@"key4"]; // "key2"と"key3"のみ登録 NSDictionary *dictionary = @{ keys[1]:@"value2", keys[2]:@"value3" }; for (NSString *key in keys) { // NSArray containsObject: BOOL is_exists1 = [dictionary.allKeys containsObject:key]; NSLog(@"dictionary.allKeys containsObject:%@ = %d",key, is_exists1); // NSDictionary objectForKey: BOOL is_exists2 = ([dictionary objectForKey:key] != nil); NSLog(@" dictionary objectForKey:%@ = %d",key, is_exists2); }
出力ログ
dictionary.allKeys containsObject:key1 = 0
dictionary objectForKey:key1 = 0
dictionary.allKeys containsObject:key2 = 1
dictionary objectForKey:key2 = 1
dictionary.allKeys containsObject:key3 = 1
dictionary objectForKey:key3 = 1
dictionary.allKeys containsObject:key4 = 0
dictionary objectForKey:key4 = 0