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
的日期,但是如何使用 过滤它>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 和 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屋!