Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 222
Sagar Kothari Avatar asked Feb 03 '10 06:02

Sagar Kothari


People also ask

How does NSDictionary work?

The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. For example, an interactive form could be represented as a dictionary, with the field names as keys, corresponding to user-entered values.

How do I know if NSDictionary is empty?

if (myDict. count) NSLog(@"Dictionary is not empty"); else NSLog(@"Dictionary is empty"); Every number that is 0 equals to @NO . Every number that is not 0 equals to @YES .

How do you append NSMutableDictionary?

Use NSMutableDictionary addEntriesFromDictionary to add the two dictionaries to a new mutable dictionary. You can then create an NSDictionary from the mutable one, but it's not usually necessary to have a dictionary non-mutable. Show activity on this post.


2 Answers

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

like image 144
mbauman Avatar answered Sep 17 '22 09:09

mbauman


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); 
like image 44
hariszaman Avatar answered Sep 17 '22 09:09

hariszaman