ios NSDictionary - 需要检查字典是否包含键值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2190056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:51:12  来源:igfitidea点击:

NSDictionary - Need to check whether dictionary contains key-value pair or not

iosobjective-cnsdictionary

提问by Sagar R. Kothari

I just need to ask something as follow. Suppose I am having a dictionary.

我只需要问一些如下。假设我有一本字典。

NSMutableDictionary *xyz=[[NSMutableDictionary alloc] init];
[xyz setValue:@"sagar" forKey:@"s"];
[xyz setValue:@"amit" forKey:@"a"];
[xyz setValue:@"nirav" forKey:@"n"];
[xyz setValue:@"abhishek" forKey:@"a"];
[xyz setValue:@"xrox" forKey:@"x"];

Now, I need to check as follows

现在,我需要检查如下

[xyz does contains key "b" value ?? pair or not?

[xyz 确实包含键“b”值??配对与否?

Question is How?

问题是如何?

The other question is How to just count total key-value pair?

另一个问题是如何计算总键值对?

Say for example NSInteger mCount=[xyz keyCounts];

比如说 NSInteger mCount=[xyz keyCounts];

回答by Matt B.

Just ask it for the objectForKey:@"b". If it returns nil, no object is set at that key.

只需询问它的objectForKey:@"b". 如果它返回nil,则不会在该键上设置任何对象。

if ([xyz objectForKey:@"b"]) {
    NSLog(@"There's an object set for key @\"b\"!");
} else {
    NSLog(@"No object set for key @\"b\"");
}

Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];. Both of these answers are documented well and easily found in the NSDictionaryclass reference ([1][2]).

编辑:至于您编辑的第二个问题,它只是NSUInteger mCount = [xyz count];. 这两个答案都有很好的记录,并且很容易在NSDictionary类参考 ( [1] [2]) 中找到。

回答by hariszaman

With literal syntax you can check as follows

使用文字语法,您可以检查如下

static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
  NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
 NSLog(@"Key pair do not exits for key: %@", kKeyToCheck);