如何检查NSDictionary或NSMutableDictionary是否包含密钥?

我须要检查dict是否有密钥。 怎么样? 数组


#1楼

是。 这种错误很常见,致使应用程序崩溃。 因此我用它在每一个项目中添加NSDictionary,以下所示: this

//.h文件代码: spa

@interface NSDictionary (AppDictionary)

- (id)objectForKeyNotNull : (id)key;

@end

//.m文件代码以下 .net

#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"];

#2楼

一个很是讨厌的问题,只是浪费了个人一些时间调试 - 你可能会发现本身提示自动完成尝试使用彷佛工做的doesContaincode

除此以外, 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

#3楼

更新的Objective-C和Clang版本具备现代语法: 字符串

if (myDictionary[myKey]) {

}

您没必要检查与nil的相等性,由于只有非零的Objective-C对象能够存储在字典(或数组)中。 而且全部Objective-C对象都是真实的值。 甚至@0 @NO@0[NSNull null]评估为true。 get

编辑:斯威夫特如今是一个东西。 it

对于Swift,你会尝试相似下面的内容

if let value = myDictionary[myKey] {

}

若是myKey在dict中,则此语法仅执行if块,若是是,则将值存储在value变量中。 请注意,这适用于0等虚假值。


#4楼

使用Swift,它将是:

if myDic[KEY] != nil {
    // key exists
}

#5楼

若是密钥不存在, objectForKey将返回nil。

相关文章
相关标签/搜索