99

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

Meet Doshi
  • 4,241
  • 10
  • 40
  • 81
sagarkothari
  • 24,520
  • 50
  • 165
  • 235

2 Answers2

199

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]).

Tony Adams
  • 691
  • 1
  • 9
  • 29
mbauman
  • 30,958
  • 4
  • 88
  • 123
  • 1
    +1 In fact, the documentation straight up says this: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/doc/uid/20000140-CBHCDIDJ – Dave DeLong Feb 03 '10 at 17:21
  • 6
    What if the key is present in the dictionary and its value is 0? Wouldn't we mistakenly think that the key isn't present in the dictionary at all? – jbx72487 Feb 01 '13 at 18:51
  • 14
    @jbx72487 Dictionaries must contain objects; `objectForKey:` returns an `id` -- a pointer to an Objective-C object. If you are storing numbers, they must be ["boxed"](http://clang.llvm.org/docs/ObjectiveCLiterals.html) into an [NSNumber](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html). Even if the NSNumber is zero or false it will be still be a valid pointer and the above code will accurately detect existence. – mbauman Feb 01 '13 at 19:45
  • not working with me it return the following: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSingleObjectArrayI objectForKey:]: unrecognized selector sent to instance 0x60000133a1c0' – Amr Angry Jan 11 '19 at 16:20
4

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); 
hariszaman
  • 8,202
  • 2
  • 40
  • 59