gpt4 book ai didi

ios - 快速控制流程

转载 作者:行者123 更新时间:2023-11-28 06:17:33 24 4
gpt4 key购买 nike

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() 直到此函数完成后才执行。

这是为什么?它必须处理线程吗?我怎样才能让 submitTapped() 在其余部分之前执行?我只是想从一个 View Controller 移动到另一个 View Controller ,同时将 self.info 发送到下一个 View Controller 。

更新:

由于下面的答案和我自己的测试,我最终弄明白了(大部分)。

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

最佳答案

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

您应该考虑使用 completionHandler 并仅在获得数据后才触发 segue。

因此您的 submitTapped 函数(可能最好将其重命名为 update 或其他)将发出网络请求,然后当它取回数据时将设置 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")
}
}

更新:

闭包、完成处理程序和异步任务一开始可能很难理解。我强烈建议您查看此 free course这是我在 Swift 中学习如何做的地方,但这需要一些时间。

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

关于ios - 快速控制流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44723958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com