我可以在完成处理程序中保存值 [英] Can I save value in a completion Handler
本文介绍了我可以在完成处理程序中保存值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是事情,我想把今天的步骤保存到完整处理器中的Core Data中。但是当我加载这个值,编译器显示为零。任何解决方案?
func fetchDataOfQuantityType(startDate:NSDate,endDate:NSDate,quantityType:HKQuantityType,completion:((NSArray,NSError! ) - > Void)!){
//用startDate和endDate初始化一个谓词
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate,endDate:endDate,options:HKQueryOptions.StrictStartDate)
//初始化一个HKStatisticsQuery
让查询:HKStatisticsQuery = HKStatisticsQuery(quantityType:quantityType,quantitySamplePredicate:predicate,options:HKStatisticsOptions.CumulativeSum,completionHandler:{(query,results,error)in
如果错误!= nil {//如果有错误打印它
println(有一个\(错误)出现)
return
}
// Mark: - 将数据保存到Core数据
var todaySteps = results.sumQuantity()。doubleValueForUnit(HKUnit.countUnit())
println今天是\(todaySteps))
var appDel:AppDelegate =(UIApplication.sharedApplication()。委托为AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newUser = NSEntityDescription.insertNewObjectForEntityForName(User,inManagedObjectContext:context)as NSManagedObject
newUser.setValue(todaySteps,forKey:todaysteps)
})
self.healthstore .executeQuery(query)
}
解决方案
看起来你不是保存上下文。尝试
var错误:NSError?
context.save(& error)
/ p>
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)
}
解决方案
This looks like you're not saving the context. Try
var error: NSError?
context.save(&error)
after you've set the value.
这篇关于我可以在完成处理程序中保存值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文