NSDictionary - Need to check whether dictionary contains key-value pair or not
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];
Solution 1:
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:
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);