我需要检查一个字典中是否存在某个键。如何实现?
我需要检查一个字典中是否存在某个键。如何实现?
objectForKey
如果对应的 key 不存在,会返回 nil。
[NSNull null]
代替。 - Ole Begemannif ([[dictionary allKeys] containsObject:key]) {
// contains key
/* Don't use this solution. Look for more details in comments. */
}
或者
if ([dictionary objectForKey:key]) {
// contains object
}
Objective-C和Clang的较新版本使用现代语法:
if (myDictionary[myKey]) {
}
不必检查是否为nil相等,因为字典(或数组)中只能存储非nil的Objective-C对象。而所有Objective-C对象都是真实值。即使是@NO
, @0
和[NSNull null]
也会被视为true。
编辑:Swift现在也可以使用了。
对于Swift,您可以尝试以下内容:
if let value = myDictionary[myKey] {
}
如果myKey在字典中,则执行if语句块,并将其值存储在value变量中。请注意,即使是falsey值(如0),此语法也适用。
if ([mydict objectForKey:@"mykey"]) {
// key exists.
}
else
{
// ...
}
#define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]
if( isNull( dict[@"my_key"] ) )
{
// do stuff
}
我喜欢Fernandes的答案,尽管您两次请求obj。
这也可以做到(与Martin的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
}
@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到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");
NSDictionary
是否包含任何键(非特定),则应使用[dictionary allKeys].count == 0
。 如果count
是0
,则NSDictionary
中没有键。 - Aleksander Azizi