在下一行执行之前,Firestore查询未完成

时间:2018-07-09 23:49:21

标签: swift google-cloud-firestore completionhandler dispatch-async

下面是放置在viewDidLoad中的代码块...

var ExerciseArray = [锻炼]

    for bodyPart in self.bodyParts {
        FIRFirestoreService.shared.getExercisesByBodyPart(by: bodyPart, returning: Exercise.self) { (exercises) in
            exerciseArray.append(exercises)
            print("Exercises: \(exercises)")
        }
    }

    chestExercises = exerciseArray[0]
    backExercises = exerciseArray[1]
    legExercises = exerciseArray[2]

    print("Chest Exercises:")

    for exercise in chestExercises!
    {
        print(exercise.name)
        print(exercise.description)
        print(exercise.mainBP)
    }

    print("Back Exercises:")

    for exercise in backExercises!
    {
        print(exercise.name)
        print(exercise.description)
        print(exercise.mainBP)
    }

    print("Leg Exercises:")

    for exercise in legExercises!
    {
        print(exercise.name)
        print(exercise.description)
        print(exercise.mainBP)
    }

当加载viewController时,for循环开始执行,并与Firebase建立连接以查询“ getExercisesByBodyPart”函数中的数据。但是,该循环无法在设置ChestExercises数组之前完成,因此我遇到了界外错误,因为所查询的对象尚未附加到exerciseArray上。 for循环中的打印功能也不会执行。

但是,当将for循环之后的其余代码块都认出时,对象将按照预期的方式加载和打印。

如何在数据完成加载并附加到数组之前停止以下代码(紧跟for循环)?

0 个答案:

没有答案