DidSelectRowAt方法中的混合顺序

问题描述

我不明白为什么调试器首先要执行方法底部,我的意思是,它首先会忽略Api调用,转到方法底部,然后再返回到Api调用
像这样:

override func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
let vc = UIStoryboard.init(name: "Main",bundle: Bundle.main).instantiateViewController(withIdentifier: "SecondVC") as? SecondVC

//Method for AlamoFire API call 1 here
apimanager.shared.getDetailsCity(city: indexPath.row){ (details) in
//code for the method
}

//Method2 for AlamoFire API call 2 here
apimanager.shared.getDetailsCountry(country: indexPath.row){ (details) in
//code for the method2
}
self.navigationController?.pushViewController(secondVC!,animated: true)
}

code for the methodcode for the method2是在所有其他事情之后产生的。
另外,有时code for the method2code for the method

之前被读取

解决方法

正如Stefan指出的那样,APIManager调用似乎是异步执行闭包的。

您可以执行以下操作:

  • 在第二个视图控制器中创建一个整数属性index
  • 当用户点击一个单元格时,实例化该视图控制器并在推动它之前设置vc.index = indexPath.row

在第二个视图控制器的viewDidLoad中:

  • 启动进度指示器
  • 向用户提供一些信息,例如“正在加载数据-请稍候”
  • 使用index值调用API管理器

在闭包中,更新UI(确保此代码在主线程中运行)

在所有关闭均已返回(可能使用调度组)之后,隐藏进度指示器