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
+2
A:
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"];
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!
Dave DeLong
2010-05-29 15:23:39
Better than neat, great.
Run Loop
2010-05-29 18:21:38
Realize that this will only work against data that has already been loaded into memory. To do the same thing for data not yet fetched you will need to de-normalize your data and store that value in the database.
Marcus S. Zarra
2010-05-29 21:55:50
@Marcus good to know, thanks! :)
Dave DeLong
2010-05-30 01:04:56