DATEADD 的 NSPredicate 语法?
有没有办法在 NSPredicate 上执行 DateAdd 或 DateDiff 函数? 谢谢你, 何塞.
is there a way to do a DateAdd or a DateDiff function on an NSPredicate?
Thank you,
Jose.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实上,有!这是一种迂回的方式,因为
NSPredicate
不直接支持它(即,你不能只是+ anInterval
到NSDate
)。幸运的是,你可以做到,而且幸运的是,我大约两天前才想出来。澄清一下:我假设您要求类似:“一个对象有一个
date
属性。我想看看这个date
属性是否是之前的某个任意间隔/另一个日期之后”。如果这就是您的意思,那么您可以做到。如果这不是您的意思,那么请澄清您的问题。开始了。在此示例中,我们将假设要评估此谓词的对象有一个名为
date
的属性,该属性返回NSDate
。我们将查看此日期是否比另一个日期至少早 1 天。我们可以通过几种不同的方法进行比较:我将采用第一种方法:
发生了什么:
为了使其正常工作,我们可以将日期对象
CAST()
NSNumber
。这会将NSDate
转换为NSNumber
,它是距参考时间点(例如 1970 年 1 月 1 日或其他)的秒数。我们对这个数字添加或减去我们的间隔,然后将新数字转换回NSDate
。然后我们可以使用常规比较运算符将新日期与比较日期进行比较。这个想法有几个不同的变体,但它们都需要将
NSDate
转换为数字(或将数字转换为NSDate
)来获取其时间间隔。狡猾的,嗯?
编辑
如果核心数据抱怨谓词的构造,请尝试逆转事情:
编辑#2
牧师偷走的雷霆:http://tumblr.com/xqorqjfrz
Actually, there is! It's a roundabout way of doing it, because
NSPredicate
doesn't support it directly (ie, you can't just+ anInterval
to anNSDate
). Fortunately, you can do it, and luckily for you, I just figured it out about 2 days ago.To clarify: I'm assuming you're asking for something like: "an object has a
date
property. I want to see if thisdate
property is some arbitrary interval before/after another date". If that's what you mean, then yes you can do it. If that's not what you mean, then please clarify your question.Here we go. In this example, we're going to assume the object against which we'll be evaluating this predicate has a property called
date
that returns anNSDate
. We are going to see if this date is at least 1 day before another date. There are a couple different ways we could do this comparison:I'm going to go with the first approach:
What's going on:
To get this to work, we can
CAST()
a date object to anNSNumber
. This is going to convert theNSDate
into anNSNumber
which is some number of seconds from a reference point in time (such as 1 Jan 1970 or whatever). To that number we add or subtract our interval, and then cast the new number back to anNSDate
. Then we can use a regular comparison operator to compare our new date against our comparison date.There are a couple different variations on this idea, but they all require casting an
NSDate
to a number (or casting a number to anNSDate
) to get its time interval.Devious, eh?
edit
If Core Data is complaining about the construct of the predicate, try reversing things:
edit #2
The thunder that The Reverend stole: http://tumblr.com/xqorqjfrz