问题
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