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

时间:2015-06-02 17:42:38

标签: swift nsfetchrequest nssortdescriptor

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

我想确保用户没有执行"保存" X分钟内的代码(测试设置为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()"返回最新日期的方法(或者我认为......):

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

我是一名新程序员,我无法解决这个问题。我希望这是愚蠢的,我只是没有看到!任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

最终弄清楚了 - 与CoreData无关。我正在设置newPlace.date = now - 'now'变量仅在程序开始时设置为NSDate(),这意味着每个输入的项目始终相同。愚蠢的错误!希望以某种方式帮助别人!