寻找一种优雅的方式来检查一个密钥是否存在于字典中

17 iphone objective-c ipad ios

可能重复:
如何检查NSDictionary或NSMutableDictionary是否包含密钥?

我可以从字典中获取一个Keys(字符串)数组,然后循环遍历它,与我要检查的Key进行字符串比较,看看该字典是否包含我寻找的密钥.

但是有更优雅的想要检查字典中是否存在密钥?

        NSArray * keys = [taglistDict allKeys];
        for (NSString *key in keys) 
        {
           // do string compare etc
        }
Run Code Online (Sandbox Code Playgroud)

-码

tro*_*foe 37

一个NSDictionary不能包含nil值,因此您可以简单地使用在键不存在时[NSDictionary objectForKey:]将返回的值nil:

BOOL exists = [taglistDict objectForKey:key] != nil;
Run Code Online (Sandbox Code Playgroud)

编辑:正如@OMGPOP所提到的,这也可以使用以下语法使用Objective-C文字:

NSDictionary *dict = @{ @"key1" : @"value1", @"key2" : @"value2" };

if (dict[@"key3"])
    NSLog(@"Exists");
else
    NSLog(@"Does not exist");
Run Code Online (Sandbox Code Playgroud)

打印:

Does not exist
Run Code Online (Sandbox Code Playgroud)


Eri*_*ric 9

Trojanfoe可能更好,但您也可以这样做:

[[taglistDict allKeys]containsObject:key]
Run Code Online (Sandbox Code Playgroud)