我可以节省完成句柄值(Can I save value in a completion Handle

2019-10-21 07:27发布

这里是东西,我想保存completionHandler今天步入核心数据。 但是,当我打开这个值时,编译器显示它为零。 任何解决方案?

 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)
}

Answer 1:

这看起来像你不保存上下文。 尝试

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

之后你已经设置的值。



文章来源: Can I save value in a completion Handler