比较Core Data日期属性的月份组件的谓词 [英] Predicate for comparing the month component of a Core Data date attribute

查看:156
本文介绍了比较Core Data日期属性的月份组件的谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个核心数据实体,它有一个日期属性。我想写一个谓词来提取特定月份内的所有日期,例如。 7月,不论年份。如何实现呢?感谢

I have a Core Data entity which has a date attribute. I would like to write a predicate to extract all dates within a specific month, e.g. July, irrespective of year. How can this be achieved? Thanks

推荐答案

您可以在实体上创建一个新方法,我们将调用 monthOfDate 。这个方法只是使用 [self dateAttribute] NSDateComponents 来提取日期的月份。

You can create a new method on your entity, which we'll call monthOfDate. This method simply uses [self dateAttribute] and NSDateComponents to extract what the month of the date is.

然后你可以写一个谓词:

Then you can write a predicate that does:

//assuming 1-based month indexing
NSPredicate * julyEntities = [NSPredicate predicateWithFormat:@"monthOfDate = 7"]; 

这里的诀窍是意识到谓词的左键会导致方法调用。因此,如果将左键盘设置为monthOfDate,它将最终调用您的 monthOfDate 方法,并使用方法的返回值作为谓词中的比较值。整洁!

The trick here is realizing that the left keypath of your predicate will result in a method invocation. So if you set the left keypath to "monthOfDate", it will end up invoking your monthOfDate method and using the return value of the method as the comparison value in the predicate. Neat!

这篇关于比较Core Data日期属性的月份组件的谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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