NSPredicate to check if an attribute of an object exits, if it does, get it

I'm not even sure if this is possible, but if it is, it can help.

I have an NSArray of NSDictionarie s.

Each dictionary has certain keys (obviously).

 Dict{ Title: WBCCount Cat: Lab } Dict{ Title: HbM Cat: Lab Sex: Male } Dict{ Title: HbF Cat: Lab Sex: Female } Dict{ Title: PC_Count Cat: CBC Sex: Female } 

I would like to filter an array with dictionaries having Cat = 'Lab' and IF Sex , since the key is present in the dictionary object to get it with Male .

In short, I can not collect

 predicateWithFormate:%@" Cat = Lab AND ( if Sex key is present, Sex = Male"; 

This will give me an array of WBC, HbM .

I don’t know if this is possible, a condition inside the predicate, but it would be a lifesaver if it were the way it happens with sending objects via the web API.

Any other way to achieve the goal, if not this, will also be great.

While we are in the Core Data topic, this should be simple: I want the attribute of an object to be able to store either NSDate , or NSNumber or NSString . Is there a simple way out?

+7
source share
2 answers

The trick here is that in an NSDictionary non-existing key simply returns nil :

 NSArray *dictionaries = @[ @{ @"Title": @"T1", @"Cat": @"Lab", @"Sex": @"Male" }, @{ @"Title": @"T2", @"Cat": @"C2" }, @{ @"Title": @"T3", @"Cat": @"Lab", @"Sex": @"Female" }, @{ @"Title": @"T4", @"Cat": @"Lab" } ]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"(Sex == nil OR Sex = 'Male') AND Cat = 'Lab'" ]; NSArray *result = [dictionaries filteredArrayUsingPredicate:pred]; 
+7
source

Another syntax (but available only for collections) to check for a key:

 NSPredicate *p = [NSPredicate predicateWithFormat:@"Sex in SELF"] 

I often use it with Parse.com

+4
source

All Articles