fabio santos
fabio santos

Reputation: 275

Cocoa - Reference a KEY in NSDictionary

I want to referenciate a ket and not what it contains on a NSDictionary like this:

key {
    14819 =     {
        contactDetails =         {
            dictionary =             {
                interests =                 {
                    Movies =   
      ...

I want to make something like this:

if([key isEqualToString:@"14819"]){
 do something
}

Can you help me?

Upvotes: 0

Views: 160

Answers (3)

Peter Hosey
Peter Hosey

Reputation: 96323

If you just want to test whether the key is present in the dictionary, use objectForKey: and test whether the object is not nil.

Getting allKeys and searching it for the key will work, but is almost certainly slower. Dictionaries are hash tables; objectForKey: uses that fact, whereas allKeys doesn't.

Upvotes: 1

AJak
AJak

Reputation: 3873

Should be able to look it up with the allKeys. Wrote a simple example, hope this helps.

NSMutableDictionary *testDictionary = [[NSMutableDictionary alloc]init];
[testDictionary setObject:@"value" forKey:@"testObject"];

BOOL containsKey = [[testDictionary allKeys] containsObject:@"testObject"];

NSLog(@"testing %d" ,containsKey);

Upvotes: 1

Asif Mujteba
Asif Mujteba

Reputation: 4656

You can use allkeys method in nsdictionary to get keys array than iterate it to compare! like this:

NSArray*keys=[dict allKeys];
for(NSString *key in keys) {
    if ([key compare@"14819"] == NSOrderedSame) {
        do something
    }
}

Upvotes: 1

Related Questions