Ron Ron - 1 month ago 7
Objective-C Question

Using NSPredicate to filter an NSMutableArray of NSDictionaries to find if a "key" exists

I have an NSMutableArray of dictionaries. I am using NSPredicate to filter through the array to find if a dictionary with a particular key exists or not.

I have referred to various examples, one of the closest is here: Using NSPredicate to filter an NSArray based on NSDictionary keys. However, I don't wish to have a value to the key. My problem is that I want to find the key first. I tried different syntaxes, but it did not help.

What I have done so far:

NSString *key = @"open_house_updated_endhour";
NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K", key];
//NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K contains [cd]", key]; Doesn't work.
//NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K == %@", key]; Won't work because it expects a value here.
NSLog(@"predicate %@",predicateString);
NSArray *filtered = [updatedDateAndTime filteredArrayUsingPredicate:predicate]; // updatedDateAndTime is the NSMutableArray

Answer

A dictionary delivers nil as value for absent key. So simply compare the key against nil.

NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K==NULL", key]; // Dictionaries not having the key
NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K!=NULL", key]; // Dictionaries having the key