简体   繁体   中英

Check key exists in NSDictionary

how can I check if this exists?:

[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"]

I want to know whether this key exists or not. How can I do that?

Thank you very much :)

EDIT: dataArray has Objects in it. And these objects are NSDictionaries.

I presume that [dataArray objectAtIndex:indexPathSet.row] is returning an NSDictionary , in which case you can simply check the result of valueForKey against nil.

For example:

if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // The key existed...

}
else {
    // No joy...

}

So I know you already selected an answer, but I found this to be rather useful as a category on NSDictionary . You start getting into efficiency at this point with all these different answers. Meh...6 of 1...

- (BOOL)containsKey: (NSString *)key {
     BOOL retVal = 0;
     NSArray *allKeys = [self allKeys];
     retVal = [allKeys containsObject:key];
     return retVal;
}

Check if it's nil:

if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // SetEntries exists in this dict
} else {
    // No SetEntries in this dict
}

this also works using Objective-C literals using the following syntax:

NSDictionary *dict = @{ @"key1" : @"value1", @"key2" : @"value2" };
if (dict[@"key2"])
NSLog(@"Exists");
else
NSLog(@"Does not exist");
if ((NSNull *)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // SetEntries exists in this dict
} else {
    // No SetEntries in this dict
}

That's the right answer.

Try this:

if ([dict objectForKey:@"bla"]) {
   // use obj
} else {
   // Do something else like create the object
}

This one does the same but with less code:

if (dataArray[indexPathSet.row][@"SetEntries"] != nil) { /* the key exists */        } 
else                                                   { /* the key doesn't exist */ }

Check dictionary contains any value. I prefer [dic allKeys].count > 0 to check.

Use the (unsigned long) option:

if ( (unsigned long)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] ) {
    // Key exist;
}else{
    // Key not exist;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM