2014-09-03 104 views
0

我的核心数据模型具有名为Item的实体,它具有名为insertedDate的日期属性。应用程序首选项设置具有让用户在插入数据库后将特定时间间隔保留为Item对象的选项。与NSDate比较相关的核心数据谓词

insertedDate属性将设置在管理对象类的awakeFromInsert方法中。

现在我有像"1 day", "2 days", "1 week", "1 month"这样的选项......如果用户选择"1 day",那么如果项目的插入日期与经过24小时的当前日期比较,则应在应用程序终止前删除这些项目。

我的问题是:如何根据它的insertedDatecurrent date之间经过的时间间隔大于用户指定的保留时间间隔选项使用谓词来获取Item对象?

非常感谢所有的帮助。

回答

1

NSPredicate支持基于NSDate属性查询对象,例如,

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"insertedDate <= %@", minInsertionDate]; 
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
[request setEntity:[NSEntityDescription entityForName:@"Item" inManagedObjectContext:context]]; 
[request setPredicate:predicate]; 

这只是让您计算minInsertionDate的值,例如,表示在所选过滤器之前插入的所有项目的时间点。为此,您可以使用NSDate的dateWithTimeIntervalSinceNow:class方法,例如获得代表1天前的日期对象...

NSTimeInterval secondsInADay = 24 * 60 * 60; 
NSDate *minInsertionDate = [NSDate dateWithTimeIntervalSinceNow:-secondsInADay]; 
+0

谢谢,但我不知道“minInsertionDate”的手段?你能解释一下吗? – 2014-09-03 12:52:54

+0

“autorelease”?? – Mundi 2014-09-03 18:59:32