我需要检查字典是否有钥匙。如何?
当前回答
在NSDictionary中检查key是否存在:
if([dictionary objectForKey:@"Replace your key here"] != nil)
NSLog(@"Key Exists");
else
NSLog(@"Key not Exists");
其他回答
if ([mydict objectForKey:@"mykey"]) {
// key exists.
}
else
{
// ...
}
如果键不存在,objectForKey将返回nil。
因为nil不能存储在Foundation数据结构中,NSNull有时表示nil。因为NSNull是一个单例对象,你可以通过直接指针比较来检查NSNull是否是存储在字典中的值:
if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }
当使用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");
推荐文章
- 为什么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编译器错误:“框架模块内的非模块化头”