【问题标题】:Core Data Predicate Related To NSDate Comparison与 NSDate 比较相关的核心数据谓词
【发布时间】:2014-09-04 05:01:51
【问题描述】:

我的核心数据模型有一个名为Item 的实体,它有一个名为insertedDate 的日期属性。应用首选项设置有选项让用户将 Item 对象自插入数据库后保持特定时间间隔。

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

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

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

非常感谢您的帮助。

【问题讨论】:

    标签: ios core-data nspredicate


    【解决方案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: 类方法,例如获取表示 1 天前的日期对象...

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

    【讨论】:

    • 谢谢,但我不知道“minInsertionDate”的含义?你能解释一下吗?
    猜你喜欢
    • 2016-10-10
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多