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

查看:424
本文介绍了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.

我知道如何使用 NSDateComponents NSCalendar NSDate c $ c>,但是如何使用 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 * 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屋!

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