NSPredicate:按NSDate属性的日期过滤对象 [英] NSPredicate: filtering objects by day of NSDate property
问题描述
我有一个核心数据模型与 NSDate
属性。我想要按天过滤数据库。我假设解决方案将涉及 NSPredicate
,但我不知道如何把它们放在一起。
I have a Core Data model with an NSDate
property. I want to filter the database by day. I assume the solution will involve an NSPredicate
, but I'm not sure how to put it all together.
我知道如何使用 NSDateComponents
和 NSCalendar $来比较两个
NSDate
c $ c>,但是如何使用 NSPredicate
?
I know how to compare the day of two NSDate
s using NSDateComponents
and NSCalendar
, but how do I filter it with an NSPredicate
?
也许我需要创建一个类别在我的 NSManagedObject
子类,可以返回一个简单的日期只有年,月和日。然后我可以在 NSPredicate
中比较。
Perhaps I need to create a category on my NSManagedObject
subclass that can return a bare date with just the year, month and day. Then I could compare that in an NSPredicate
. Is this your recommendation, or is there something simpler?
推荐答案
给定一个NSDate * startDate em> endDate 和NSManagedObjectContext * moc :
Given a NSDate * startDate and endDate and a NSManagedObjectContext * moc:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", startDate, endDate];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
这篇关于NSPredicate:按NSDate属性的日期过滤对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!