user6631314
user6631314

Reputation: 1958

IOS/Objective-C/Core Data: NSPredicates with Complicated Conditional logic

I am using an NSPredicate to filter an entity in coredata. Most of the examples Apple and others provides do not embody the complicated logic you can do in SQL but since the predicates resolve to sql, it seemed to me there might be more that is possible than is readily viewable in the apple docs.

In particular, I would like to filter managed objects by one date if a certain attribute is true but an earilier date, if the attribute is false.

Something like:

NSDate *now = [NSDate date];
NSDate *lastYear =   [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitYear value:-1 toDate:now options:0];

NSPredicate *myPred=  [NSPredicate predicateWithFormat:@"new==1 ? date >= %@ :date>=%@", now,lastYear];

Is there any way to put conditional logic inside an NSPredicate?

Upvotes: 0

Views: 47

Answers (2)

Musavir Parambil
Musavir Parambil

Reputation: 120

Try this

[NSPredicate predicateWithFormat:@"(new == 1 AND date >= %@) OR (new == 0 AND date >= %@)", now, lastYear];

Upvotes: 0

johnyu
johnyu

Reputation: 2151

This should be achievable with following format

@"(new == 1 AND date >= %@) OR (new == 0 AND date >= %@)", now, lastYear

Hope it helps.

Upvotes: 1

Related Questions