How to check if an NSDictionary or NSMutableDictionary contains a key?

前端 未结 16 2857
北海茫月
北海茫月 2020-11-28 00:52

I need to check if an dict has a key or not. How?

16条回答
  •  忘掉有多难
    2020-11-28 01:46

    One very nasty gotcha which just wasted a bit of my time debugging - you may find yourself prompted by auto-complete to try using doesContain which seems to work.

    Except, doesContain uses an id comparison instead of the hash comparison used by objectForKey so if you have a dictionary with string keys it will return NO to a 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
    

提交回复
热议问题