这就是事情,我想将今天的步骤保存到completionHandler中的Core Data中。但是当我加载这个值时,编译器显示它为零。任何解决方案?
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)
}
答案 0 :(得分:0)
这看起来就像你没有保存上下文。尝试
var error: NSError?
context.save(&error)
设置值后。