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

2 Answers 2

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

4
  • 1
    +1 In fact, the documentation straight up says this: developer.apple.com/mac/library/documentation/Cocoa/Reference/… Feb 3, 2010 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 1, 2013 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" into an NSNumber. 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 1, 2013 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, 2019 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); 

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.