我需要检查字典是否有键。如何?
16 回答
objectForKey
如果键不存在,将返回 nil。
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,您可以尝试以下操作
if let value = myDictionary[myKey] {
}
如果 myKey 在 dict 中,则此语法只会执行 if 块,如果是,则值存储在 value 变量中。请注意,这甚至适用于像 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。
这也应该这样做(或多或少与马丁的 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
是的。这种错误很常见,会导致应用程序崩溃。所以我使用在每个项目中添加 NSDictionary 如下:
//.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"];
一个非常讨厌的问题,只是浪费了我的一点调试时间——你可能会发现自动完成提示自己尝试使用doesContain
似乎可行的方法。
除了,doesContain
使用 id 比较而不是使用的哈希比较,objectForKey
因此如果您有一个带有字符串键的字典,它将返回 NO 到 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
使用 Swift,它将是:
if myDic[KEY] != nil {
// key exists
}
检查 NSDictionary 中是否存在键:
if([dictionary objectForKey:@"Replace your key here"] != nil)
NSLog(@"Key Exists");
else
NSLog(@"Key not Exists");
因为 nil 不能存储在 Foundation 数据结构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
}
我建议您将查找结果存储在临时变量中,测试临时变量是否为 nil,然后使用它。这样你就不会两次看同一个对象:
id obj = [dict objectForKey:@"blah"];
if (obj) {
// use obj
} else {
// Do something else
}
if ([MyDictionary objectForKey:MyKey]) {
// "Key Exist"
}
正如 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 ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
//do something if doesn't exist
}
这是用于嵌套字典结构