8

I'm using a NSFetchedResultsController and a UITableViewController to populate a UITableView from a CoreData database.

I have a NSDate object saved into this Date attribute labeled "startTime". Then I'm trying to only pull todays's data by using a NSPredicate that looks like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"startDate == %@",
                          todaysDate];

I'm getting zero results. I understand this because a NSDate object just hold the number of seconds or milliseconds or whatever since Jan 1 1970 right? So comparing 1111111111111 and 1111111111112, while on the same day, are two distinct NSDate objects that aren't equal.

So, how could the NSPredicate be formatted so that it would do it? I'm going to guess its creating two NSDate objects: one that is at 12am last night, and another for 12am tonight and compare startDate and see if its between these two NSDates.

I'm kind of new to NSPredicate, so how could this be accomplished?

Kev
  • 118,037
  • 53
  • 300
  • 385
Robby Cohen
  • 497
  • 6
  • 21
  • You should put your solution in an answer instead of putting it inside the question. – yuji Feb 22 '12 at 19:45
  • Can't @yuji because I don't have enough rep yet. – Robby Cohen Feb 22 '12 at 20:28
  • Maybe you could put **your** solution in an answer. In the meantime I have edited it out seeing as you've already accepted yuji's answer. You can recover your solution by viewing the revision history. Thanks. – Kev Aug 10 '12 at 23:45

1 Answers1

24

Use NSCompoundPredicate.

NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:@"startDate > %@", firstDate];
NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"startDate < %@", secondDate];

NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:firstPredicate, secondPredicate, nil]];

Where firstDate is 12am this morning and secondDate is 12am tonight.

P.S. Here's how to get 12am this morning:

NSCalendar *calendar = [NSCalendar calendar]; // gets default calendar
NSCalendarComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, and day for today's date
NSDate *firstDate = [calendar dateFromComponents:components]; // makes a new NSDate keeping only the year, month, and day

To get 12am tonight, change components.day.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
yuji
  • 16,695
  • 4
  • 63
  • 64
  • 1
    Thanks very much - couple of small typos - andPredicateWithSubpredicates (lower case P) and use NSDateComponents instead of NSCalendarComponents – amergin Apr 21 '13 at 16:26