方法乱序触发

Methods firing out of order

我的 HealthAlgorithm class 中有 updateHeightupdateWeightupdateBMI 方法。然后我尝试按 ViewController.swift

中的顺序调用它们

HealthAlgorithm.swift:

//MARK: Properties
var healthManager:HealthManager?
var kUnknownString = "Unknown"
var bmi:Double?
var height:HKQuantitySample?
var weight:HKQuantitySample?

func updateHeight() {       

    // 1. Construct an HKSampleType for weight
    let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)

    // 2. Call the method to read the most recent weight sample
    HealthManager().readMostRecentSample(sampleType!, completion: { (mostRecentHeight, error) -> Void in

        if( error != nil )
        {
            print("Error reading height from HealthKit Store: \(error.localizedDescription)")
            return
        }
        var heightLocalizedString = self.kUnknownString
        self.height = mostRecentHeight as? HKQuantitySample
        print(self.height)
        // 3. Format the height to display it on the screen
        if let meters = self.height?.quantity.doubleValueForUnit(HKUnit.meterUnit()) {
            let heightFormatter = NSLengthFormatter()
            heightFormatter.forPersonHeightUse = true
            heightLocalizedString = heightFormatter.stringFromMeters(meters)
        }
    })
}

func updateBMI(){
    if weight != nil && height != nil {
        // 1. Get the weight and height values from the samples read from HealthKit
        let weightInKilograms = weight!.quantity.doubleValueForUnit(HKUnit.gramUnitWithMetricPrefix(.Kilo))
        let heightInMeters = height!.quantity.doubleValueForUnit(HKUnit.meterUnit())
        bmi  = ( weightInKilograms / ( heightInMeters * heightInMeters ) )
    }
    print("BMI: ",bmi)
}

我在 ViewController.swift 中这样调用这些方法:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    HealthAlgorithm().updateHeight()
    HealthAlgorithm().updateWeight()
    HealthAlgorithm().updateBMI()
}

问题是 BMI 返回为 nil。发生这种情况的原因是 updateBMI 方法在 updateHeightupdateWeight 方法之前触发。

我在updateHeight方法中定义变量后立即使用print(self.height),在updateBMI方法中定义bmi变量后立即使用print("BMI: ", bmi) .由于我首先调用 updateHeightprint(self.height) 应该在 print("BMI: ", bmi) 之前发生,但由于某种原因,BMI: nil 首先返回,这对我来说毫无意义。

方法没有被乱序调用。问题是函数异步完成。您需要从完成处理程序调用依赖代码。