我需要检查字典是否有钥匙。如何?
if ([[dictionary allKeys] containsObject:key]) {
// contains key
}
or
if ([dictionary objectForKey:key]) {
// contains object
}
我建议您将查找结果存储在一个临时变量中,测试临时变量是否为nil,然后使用它。这样你就不会重复查找同一个对象:
id obj = [dict objectForKey:@"blah"];
if (obj) {
// use obj
} else {
// Do something else
}
因为nil不能存储在Foundation数据结构中,NSNull有时表示nil。因为NSNull是一个单例对象,你可以通过直接指针比较来检查NSNull是否是存储在字典中的值:
if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }
我喜欢费尔南德斯的回答,尽管你问了两次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给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
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。
当使用JSON字典时:
#define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]
if( isNull( dict[@"my_key"] ) )
{
// do stuff
}
在NSDictionary中检查key是否存在:
if([dictionary objectForKey:@"Replace your key here"] != nil)
NSLog(@"Key Exists");
else
NSLog(@"Key not Exists");
正如Adirael建议objectForKey检查键的存在,但当你调用objectForKeyin可空字典时,应用程序崩溃,所以我从下面的方式修复了这个问题。
- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;
if (dictionary && (object != [NSNull null])) {
self.name = [dictionary objectForKey:@"name"];
self.age = [dictionary objectForKey:@"age"];
}
return self;
}
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
}
if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
//do something if doesn't exist
}
这是针对嵌套的字典结构
推荐文章
- Xcode 4挂在“附加到(应用程序名称)”
- 以编程方式创建segue
- 在Objective-C中@synchronized如何锁定/解锁?
- Xcode构建失败“架构x86_64未定义的符号”
- 动态改变UILabel的字体大小
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持
- 新的自动引用计数机制是如何工作的?
- 如何测试对象在Objective-C中的类?
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 从Cocoa应用程序执行一个终端命令
- Swift编译器错误:“框架模块内的非模块化头”
- 从父iOS访问容器视图控制器
- 自定义dealloc和ARC (Objective-C)
- 调整UITableView的大小以适应内容
- 在代码中为UIButton设置一个图像