don*_*ile 453 objective-c foundation
我需要检查dict是否有密钥.怎么样?
Adi*_*ael 762
objectForKey 如果密钥不存在,则返回nil.
Ale*_*iks 162
if ([[dictionary allKeys] containsObject:key]) {
// contains key
}
Run Code Online (Sandbox Code Playgroud)
要么
if ([dictionary objectForKey:key]) {
// contains object
}
Run Code Online (Sandbox Code Playgroud)
And*_*oos 98
更新的Objective-C和Clang版本具有现代语法:
if (myDictionary[myKey]) {
}
Run Code Online (Sandbox Code Playgroud)
您不必检查与nil的相等性,因为只有非零的Objective-C对象可以存储在字典(或数组)中.并且所有Objective-C对象都是真实的值.甚至@NO,@0并[NSNull null]评估为真.
编辑:斯威夫特现在是一个东西.
对于Swift,你会尝试类似下面的内容
if let value = myDictionary[myKey] {
}
Run Code Online (Sandbox Code Playgroud)
如果myKey在dict中,则此语法仅执行if块,如果是,则将值存储在value变量中.请注意,这适用于0等虚假值.
Chr*_*heD 22
if ([mydict objectForKey:@"mykey"]) {
// key exists.
}
else
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
使用JSON词典时:
#define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]
if( isNull( dict[@"my_key"] ) )
{
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
我喜欢费尔南德斯的答案,即使你要求两次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
}
Run Code Online (Sandbox Code Playgroud)
Martin和这个答案都适用于iPad2 iOS 5.0.1 9A405
小智 5
是.这种错误很常见,导致应用程序崩溃.所以我用它在每个项目中添加NSDictionary,如下所示:
//.h文件代码:
@interface NSDictionary (AppDictionary)
- (id)objectForKeyNotNull : (id)key;
@end
Run Code Online (Sandbox Code Playgroud)
//.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
Run Code Online (Sandbox Code Playgroud)
在代码中,您可以使用如下:
NSStrting *testString = [dict objectForKeyNotNull:@"blah"];
Run Code Online (Sandbox Code Playgroud)
一个非常讨厌的问题,只是浪费了我的一些时间调试 - 你可能会发现自己提示自动完成尝试使用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
Run Code Online (Sandbox Code Playgroud)