我需要检查字典是否有钥匙。如何?
当前回答
if ([[dictionary allKeys] containsObject:key]) {
// contains key
}
or
if ([dictionary objectForKey:key]) {
// contains object
}
其他回答
if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
//do something if doesn't exist
}
这是针对嵌套的字典结构
当使用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");
是的。这类错误非常常见,会导致应用程序崩溃。所以我使用添加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"];
我喜欢费尔南德斯的回答,尽管你问了两次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
推荐文章
- 在实现API时,我如何避免在块中捕获自我?
- 从另一个应用程序打开设置应用程序
- 使用NSURLSession发送POST请求
- 如何更改导航栏上“后退”按钮的标题
- 有没有办法从UITableView中移除分隔线?
- 如何在Objective-C中声明类级属性?
- 在Objective-C中@property保留,赋值,复制,非原子
- 我如何在NSAttributedString中创建一个可点击的链接?
- 停止UIWebView垂直“弹跳”?
- 对未渲染的视图进行快照,结果是一个空快照
- 开始使用instancetype而不是id是否有益?
- 我可以强制UITableView隐藏分隔符之间的空单元格吗?
- 为什么Objective-C文件使用。m扩展名?
- Objective-C for Windows
- 获得推送通知,而应用程序在前台iOS