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

IosObjective CNsdictionary

Ios Problem Overview


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?

Question is How?

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

Say for example NSInteger mCount=[xyz keyCounts];

Ios Solutions


Solution 1 - Ios

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

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 NSDictionary class reference ([1] [2]).

Solution 2 - Ios

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); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSagar KothariView Question on Stackoverflow
Solution 1 - IosmbaumanView Answer on Stackoverflow
Solution 2 - IoshariszamanView Answer on Stackoverflow