核心数据谓词与日期 [英] Core Data- predicate with dates

查看:134
本文介绍了核心数据谓词与日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉尝试为最近完成任务编写谓词,即显示任务是否在过去7天内完成。我想我需要做这样的事情:如果NOW< dateCompleted + 7天。

I'm stumped trying to write a predicate for "Recently Completed" tasks, i.e. show the task if it was completed within the last 7 days. I think I need to do something like this: "if NOW < dateCompleted + 7 days".

dateCompleted是表上的一个属性,但我不知道我应该如何得到它的值,并从谓词中添加7天。我想我需要先获取属性值,然后写入NSPredicate,但如何?我现在没有访问managedObject。

The dateCompleted is an attribute on the table, but I'm not sure how I'm supposed to get it's value and add 7 days to it from within the predicate. I guess I need to fetch the attribute value first before writing the NSPredicate, but how? I don't have access to the managedObject at this point.

这可能是关闭的解决方案,但我不知道如何定义'oneWeek',我不认为你可以只添加值,当定义谓词

This might be close the solution, but I can't figure out how to define 'oneWeek' and I don't think you can just add values when defining the predicate:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"%@ < todoCompletedDate + %@", [NSDate date], oneWeek];


推荐答案

首先,您需要定义日期范围。为此,您需要从今天的日期开始,然后添加几周的天数来找到有效范围的结束。一旦你有了这个范围,你可以构建你的谓词,以找到到期日期> =开始和< =结束的所有任务。下面是一些代码中的摘要,我写了一些非常相似的...

Firstly you need to define your date range. To do that you'll want to start with today's date and then add a weeks worth of days to find the end of the valid range. Once you have that range you can build your predicate to find all tasks with a due date >= start and <= end. Here's an extract from some code I've written to do something very similar...

NSDate *today = [NSDate date];
NSDate *startOfToday = [DateHelper startOfDay:today];
NSDate *endOfWeek = [DateHelper addDaysToDate:today daysToAdd:6];
return [NSPredicate predicateWithFormat:@"(dueDate >= %@) AND (dueDate <= %@) AND complete == 0", startOfToday, endOfWeek];

这篇关于核心数据谓词与日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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