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 NSDate
s.
I'm kind of new to NSPredicate
, so how could this be accomplished?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With