NSPredicate and CoreData - decide if a Date attribute is “today” (or between last night 12am to tonight 12am) on iOS

我与影子孤独终老i 提交于 2019-11-30 03:45:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9401466/nspredicate-and-coredata-decide-if-a-date-attribute-is-today-or-between-las

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!