Search code examples
swiftnsfetchrequestnssortdescriptor

CoreData Fetch (Sort by Date) - Doesn't update for new data?


I have a program which has CoreData entities including a NSDate field that indicates date each object was saved.

I want to make sure that the user hasn't executed the "saving" code within X minutes (in testing set to 1). If it is within X minutes, don't add additional object to context, just execute the rest of the code... otherwise, save then execute.

Here is the beginning of the code that creates a new object:

func makePlaces (NSObject: AnyObject) {

    let objectCount = checkCoreForObjects()

    //if objects exist in coredata
    if objectCount > 0 {
        //check what the difference from latest entry is
        var latestPlace = getLatestPlace()
        println(latestPlace[0].date.timeIntervalSinceNow/60)
        if floor(latestPlace[0].date.timeIntervalSinceNow/60) >= -1 {
            println("within 1 minute")
            return
        } else {
            println("more than 1 minute")
        }
    }

    let newPlace = NSEntityDescription.insertNewObjectForEntityForName("Place",
        inManagedObjectContext: self.managedObjectContext!) as! Place

    newPlace.date = now
//lots of other working code has been removed here for clarity


self.managedObjectContext!.save(nil)

This is the "getLatestPlace()" method that returns the latest date (or so I think...):

func getLatestPlace () -> [Place] {
    var error: NSError? = nil
    let request = NSFetchRequest(entityName: "Place")
    let sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
    let sortDescriptors = [sortDescriptor]
    request.sortDescriptors = sortDescriptors
    request.fetchLimit = 1
    var latestPlace = self.managedObjectContext?.executeFetchRequest(request, error: &error) as! [Place]
    println("latestPlaces count: \(latestPlace.count)")
    println("latesttime is \(latestPlace[0].date)")
    return latestPlace
}

This is the console readout:

//FIRST SAVE ATTEMPT
latestPlaces count: 1
latest date save is 2015-06-02 17:02:00 +0000
-24.5014304161072
more than 1 minute

//SECOND SAVE ATTEMPT (was within 1 min, latest date save did update)
latestPlaces count: 1
latest date save is 2015-06-02 17:26:17 +0000
-0.463125466307004
within 1 minute

//THIRD SAVE ATTEMPT (was after 1 min)
latestPlaces count: 1
latest date save is 2015-06-02 17:26:17 +0000
-1.39080496629079
more than 1 minute

//FOURTH SAVE ATTEMPT (was within 1 min, latest date save DIDNT update?!)
latestPlaces count: 1
latest date save is 2015-06-02 17:26:17 +0000
-1.47449685037136
more than 1 minute

TLDR: Why is "Fourth Save Attempt" in the console not properly indicating that the save attempt was within 1 minute of the most recent object in core data? It just lets me spam save after the first minute without updating the date to the most recent value.

I'm a new programmer and I can't figure this out. I hope it is something stupid I am just not seeing! Any help appreciated.


Solution

  • Eventually figured it out - had nothing to do with CoreData. I was setting newPlace.date = now -- that 'now' variable was being set to NSDate() only at the start of the program, meaning it was always the same for each entered item. Stupid mistake! Hope that helps someone else somehow!