NSPredicate:按 NSDate 属性的日期过滤对象 [英] NSPredicate: filtering objects by day of NSDate property

查看:19
本文介绍了NSPredicate:按 NSDate 属性的日期过滤对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 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.

我知道如何使用 NSDateComponentsNSCalendar 比较两个 NSDate 的日期,但是如何使用 过滤它>NSPredicate?

I know how to compare the day of two NSDates 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 * startDateendDate 和一个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆