Reputation: 1493
My core data model have a entity called Item
, it have a date attribute called insertedDate
. The app preference settings have options let user keeps Item
object for a specific time interval since it inserted into database.
The insertedDate
attribute will be set in the awakeFromInsert
method of managed object class.
Now i have options like "1 day", "2 days", "1 week", "1 month"
...... if user chooses "1 day"
, then if item's insertedDate compare to current date elapsed than 24 hours, these items should be deleted before app terminates.
My question is : How to fetch Item objects according to the time interval elapsed between it's insertedDate
and current date
greater than user specified keep time interval option using predicate?
Big thanks for all the help.
Upvotes: 0
Views: 1024
Reputation: 13807
NSPredicate supports querying objects based on NSDate properties e.g.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"insertedDate <= %@", minInsertionDate];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Item" inManagedObjectContext:context]];
[request setPredicate:predicate];
This just leaves how you compute the value of the minInsertionDate, e.g. the point in time that represents all items inserted prior to the chosen filter. For this you can use NSDate's dateWithTimeIntervalSinceNow: class method, e.g. to get a date object representing 1 day ago...
NSTimeInterval secondsInADay = 24 * 60 * 60;
NSDate *minInsertionDate = [NSDate dateWithTimeIntervalSinceNow:-secondsInADay];
Upvotes: 1