我需要检查dict是否有密钥。如何?

有帮助吗?

解决方案

objectForKey 如果不存在键,将返回无。

其他提示

if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

或者

if ([dictionary objectForKey:key]) {
    // contains object
}

Objective-C和Clang的最新版本为此具有现代语法:

if (myDictionary[myKey]) {

}

您不必检查NIL的平等,因为只有非nil Objective-C对象可以存储在字典(或数组)中。所有Objective-C对象都是真实的价值观。甚至 @NO, @0, , 和 [NSNull null] 评估为真实。

编辑:Swift现在是一回事。

对于Swift,您会尝试以下内容

if let value = myDictionary[myKey] {

}

此语法仅在MyKey在DICT中以及该值时才执行IF Block,则该值将存储在值变量中。请注意,这甚至适用于诸如0之类的假值。

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
}

马丁和这个答案都在ipad2 iOS 5.0.1 9A405上工作

一个非常令人讨厌的陷阱,浪费了我的时间调试 - 您可能会发现自己是由自动完成的提示 doesContain 这似乎有效。

除了, doesContain 使用ID比较而不是使用的哈希比较 objectForKey 因此,如果您有带有字符串键的字典,它将返回到 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
}

是的。这种错误非常普遍,并导致应用程序崩溃。因此,我用以下每个项目中添加Nsdixtionary:

//.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");

因为零不能存储在基础数据结构中 NSNull 有时代表一个 nil. 。因为 NSNull 是单身对象,您可以检查是否是否 NSNull 是通过使用直接指针比较存储在字典中的值:

if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }

Swift 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
}

我建议您将查找的结果存储在温度变量中,测试温度变量是否为零,然后使用它。这样,您就不会两次看相同的对象:

id obj = [dict objectForKey:@"blah"];

if (obj) {
   // use obj
} else {
   // Do something else
}

正如阿迪拉尔(Adirael)所建议的 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"
} 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top