Can I save value in a completion Handler

浪尽此生 提交于 2019-12-11 13:26:19

问题


here is the thing, I wants to save the today steps into Core Data in completionHandler. But while I load this value,the complier shows it a nil. any solution?

 func fetchDataOfQuantityType(startDate: NSDate, endDate: NSDate, quantityType: HKQuantityType, completion:((NSArray, NSError!) -> Void)!)  {

    // initial a predicate with startDate and endDate
    let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.StrictStartDate)

    // initialize a HKStatisticsQuery
    let query: HKStatisticsQuery = HKStatisticsQuery(quantityType: quantityType, quantitySamplePredicate: predicate, options: HKStatisticsOptions.CumulativeSum, completionHandler: { (query, results, error) in

        if error != nil { // if there is an error print it
            println("there is a \(error) occur")
            return
        }
        // Mark: - Saving the data in to Core data

        var todaySteps = results.sumQuantity().doubleValueForUnit(HKUnit.countUnit())
        println("The totalstep for today is \(todaySteps)")
            var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
            var context: NSManagedObjectContext = appDel.managedObjectContext!
            var newUser = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: context) as NSManagedObject
            newUser.setValue(todaySteps, forKey: "todaysteps")
            })
    self.healthstore.executeQuery(query)
}

回答1:


This looks like you're not saving the context. Try

var error: NSError?
context.save(&error)

after you've set the value.



来源:https://stackoverflow.com/questions/27074421/can-i-save-value-in-a-completion-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!