Sj.
Sj.

Reputation: 1724

Date comparison using Predicate in NSFetchedResultsController with CoreData

My CoreData Entity has two attributes date1 and date2. CoreData is backed up by an Sql based store. How can I fetch entities having same date1 and date2? (Ignoring the time. But while storing we cannot omit the time.)

I tried [NSPredicate predicateWithFormat:@"date1/86400 == date2/86400"] , but it is not working.

Can I achieve this along with NSFetchedResultsController, or Do I need to do in-memory filtering using blocks/functions ?

Upvotes: 0

Views: 209

Answers (1)

Michał Ciuba
Michał Ciuba

Reputation: 7944

Using NSFetchRequest (or NSFetchedResultsController) with SQLite store, you are able only to do simple equality check or comparison (date1 > date2 etc.) in a predicate. You can use in-memory filtering, but you can also use a workaround to do the filtering while fetching.

Just add another two NSDate properties to your entity, let's call them: day1 and day2. Then each time you save date1 and date2, save a "stripped" date (without hours, minutes, seconds) to day1 and day2. You can choose an arbitrary time in a day, like midday. Then simply use @"day1 = day2" in the predicate. This will improve performance and make working with NSFetchedResultsController easier, but also require more space for the storage.

As a side note, doing date calculations "by hand" like dividing by 86400 can fail because one day does not always equal 24 hours.

Upvotes: 1

Related Questions