快速控制流程

时间:2017-06-23 14:32:08

标签: ios swift controller segue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    submitTapped()
    if let scheduleController = segue.destination as? ScheduleController {
        scheduleController.jsonObject = self.info
    }
}

在submitTapped()中,为self.info分配一个值。但是当我运行我的应用程序时,self.info被报告为" nil"。我尝试在三行中的每一行设置断点,似乎submitTapped()在此函数完成之后才会执行。

这是为什么?是否必须处理线程?如何让commitTapped()在其余部分之前执行?我只是尝试从一个视图控制器移动到另一个视图控制器,同时还将self.info发送到下一个视图控制器。

更新:

由于下面的答案+我自己的测试,我最终搞清楚了(大部分)。

@IBAction func submitTapped() {
    update() { success in
        if success {
            DispatchQueue.main.async {
                self.performSegue(withIdentifier: "showScheduler", sender: nil)
            }
        }
    }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // I'll probably check the segue identifier here once I have more "actions" implemented
    let destinationVC = segue.destination as! ScheduleController
    destinationVC.jsonObject = self.info
}

public func update(finished: @escaping (Bool) -> Void) {
    ...
    self.info = jsonObject //get the data I need
    finished(true)
    ...
}

1 个答案:

答案 0 :(得分:1)

网络请求是在后台发生的异步任务,需要一些时间才能完成。您的prepareForSegue方法调用将在数据从网络返回之前完成。

您应该查看使用completionHandler,并且只有在获得数据后才触发segue。

所以你的submitTapped函数(可能最好将其重命名为更新或其他东西)将发出网络请求,然后当它获取数据时将设置self.info属性,然后调用performSegueWithIdentifier。

func update(completion: (Bool) -> Void) {
    // setup your network request. 
    // perform network request, then you'll likely parse some JSON

    // once you get the response and parsed the data call completion
    completion(true)
}

update() { success in
    // this will run when the network response is received and parsed.
    if success {
        self.performSegueWithIdentifier("showSchedular")
    }
}

更新:

Closures,Completion处理程序一开始就很难理解异步任务。我强烈建议您查看这个free course,这是我在Swift中学习如何操作的地方,但需要一些时间。

video tutorial可以更快地教你基础知识。