JZ.
JZ.

Reputation: 21877

How do I fetch items that are n Days old using CoreData in Swift?

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

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70946

Assuming that date is an attribute of your Video entity and that it contains valid values for this query,

  • You need to use a negative number for timeIntervalSinceNow: to get a date in the past. You're using a date in the future.
  • There are more than 3600 seconds in a day, you probably meant 86400, or double that for 2 days. But that's still not a great approach.

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

Related Questions