方法无序发射

时间:2015-10-23 18:58:58

标签: ios swift function methods health-kit

我的updateHeight课程中有updateWeightupdateBMIHealthAlgorithm方法。然后我尝试在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方法之前触发。

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

1 个答案:

答案 0 :(得分:4)

这些方法没有被无序调用。问题是该函数异步完成。您需要从完成处理程序调用相关代码。