CoreData Fetch(按日期排序)- 不更新新数据?

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

我有一个包含 CoreData 实体的程序,其中包含一个 NSDate 字段,指示每个对象的保存日期。

我想确保用户没有在 X 分钟内执行 "saving" 代码(在测试中设置为 1)。如果在 X 分钟内,不要向上下文添加额外的对象,只需执行其余代码...否则,保存然后执行。

这是创建新对象的代码的开头:

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)

这是 "getLatestPlace()" 方法 returns 最晚日期(或者我认为...):

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
}

这是控制台读数:

//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:为什么控制台中的 "Fourth Save Attempt" 没有正确指示保存尝试是在核心数据中最近对象的 1 分钟内?它只是让我在第一分钟后保存垃圾邮件而不将日期更新为最新值。

我是一个新程序员,我搞不懂这个。我希望这是我没有看到的愚蠢的东西!任何帮助表示赞赏。

最终弄明白了 - 与 CoreData 无关。我正在设置 newPlace.date = 现在——那个 'now' 变量只在程序开始时被设置为 NSDate(),这意味着它对于每个输入的项目总是相同的。愚蠢的错误!希望能以某种方式帮助别人!