0
votes

I am trying to filter an NSArray of objects according to values in a specific key. My objects have a date when they were created, so basically, I want to create objects for three months, but show only one per week, therefore, I need to filter the results to show the objects according to the date.

I have a database with all the information I need to create these objects. My first idea was to create a period key in this database, specifying how long the object will be available. For example, object 1 would have the number 604800 (timeInterval for one week) in the "period"key. Now, for retrieving these objects, I would need to compare two keys, the createdAt, which is an NSDate, and the timeInterval which would be a NSNumber.

I tried to create two NSDatecolumns in my table and use predicate: [NSPredicate predicateWithFormat:"(startDate <= %@) AND (endDate >= %@"), today, today];, and although I would have a lot more work to create the objects with these two added columns, the mentioned predicate didn't work, I'm not sure why.

Anyway, I'm looking for a simple solution and some code as well.

1
Your " look misplaced.. check them once - Akshat Singhal
Yes, sorry, that was a typing mistake, but wasn't the problem. - Jorge
If you are passing today two times (<= and >=), wouldn't that give you only exact equality (==)? - David Rönnqvist
What is the structure(properties and it classes) of objects stored in the array? May be you need change predicate to [NSPredicate predicateWithFormat:@"(SELF.startDate <= %@) AND (SELF.endDate >= %@)", today, today]; or use sortedArrayUsingFunction:. - Ruslan Soldatenko

1 Answers

0
votes

You don't have to create and fill extra columns, because you can do simple arithmetic in the predicate, for example:

[NSPredicate predicateWithFormat:@"createdAt <= %@ AND createdAt + period >= %@", today, today]

where createdAt is a "Date" attribute and period a "Double" attribute.

Update: As I just realized, this works only if you also set

[request setIncludesPendingChanges:NO];

which means that the fetch is executed against the saved database only, but does not include unsaved changes.