我需要检查字典是否有钥匙。如何?
当前回答
我喜欢费尔南德斯的回答,尽管你问了两次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
其他回答
if ([MyDictionary objectForKey:MyKey]) {
// "Key Exist"
}
正如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
}
使用Swift,它将是:
if myDic[KEY] != nil {
// key exists
}
if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
//do something if doesn't exist
}
这是针对嵌套的字典结构
推荐文章
- 为什么ARC仍然需要@autoreleasepool ?
- 首先添加一个UIView,甚至是导航栏
- 我如何改变UIButton标题颜色?
- iOS -构建失败,CocoaPods无法找到头文件
- Xcode 4挂在“附加到(应用程序名称)”
- 以编程方式创建segue
- 在Objective-C中@synchronized如何锁定/解锁?
- Xcode构建失败“架构x86_64未定义的符号”
- 动态改变UILabel的字体大小
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持
- 新的自动引用计数机制是如何工作的?
- 如何测试对象在Objective-C中的类?
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 从Cocoa应用程序执行一个终端命令
- Swift编译器错误:“框架模块内的非模块化头”