Reputation: 21877
I'm trying to use CoreData to find records that are greater than 2 days old, in order to do some processing. How can I use Swift to find records that are greater than two days old?
This is my attempt:
class func findOldPics() {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context: NSManagedObjectContext = appDel.managedObjectContext!
var managedObject: NSManagedObject!
var fetchRequest = NSFetchRequest(entityName: "Video")
var date = NSDate(timeIntervalSinceNow: 3600)
fetchRequest.predicate = NSPredicate(format: "date <= %@", date)
if let fetchResults = appDel.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] {
if fetchResults.count != 0{
NSLog("***************** found film! updating status %@", fetchResults)
} else {
println("***************** no films found")
} // else
}
}
Upvotes: 0
Views: 364
Reputation: 70946
Assuming that date
is an attribute of your Video
entity and that it contains valid values for this query,
timeIntervalSinceNow:
to get a date in the past. You're using a date in the future.A better way to get a date 2 days ago is to use NSCalendar
rather than assuming some number of seconds. What if daylight savings time began or ended in the past 2 days? You can reliably get a date 2 days before now with:
let twoDaysAgo = NSCalendar.currentCalendar().dateByAddingUnit(.DayCalendarUnit,
value: -2, toDate: NSDate(), options: nil)
Upvotes: 1