我的应用程序有以下流程:
- 视图控制器1为TableView提供标题
- 用户选择TableView行
- 视图控制器1指示模型加载所选TableView行的完整数据
- 模型将数据传回视图控制器1
- 视图控制器1将该数据作为分段的一部分传递给视图控制器2
这就是我向视图控制器2:传递数据的方式
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let destination = segue.destination as? UINavigationController else {
return
}
guard let finalDestination = destination.viewControllers.first as? SegmentedControlViewController else {
return
}
if let indexPath = tableView.indexPathForSelectedRow {
let documentId = documentIdArray[indexPath.row]
finalDestination.documentId = documentId
print(documentID) // documentId is not nil and is passed to the next view controller successfully
model.getRecipeSelected(docId: documentId) // the output of this is entireRecipe
finalDestination.entireRecipe = entireRecipe
print(entireRecipe) // entireRecipe is nil
}
}
该应用程序崩溃,因为View Controller 2正试图处理尚未存在的数据。如何确保model.getRecipeSelected(docId: documentId)
获取数据并将其传递给视图控制器2,然后再进行切换?
注意:我已经通过将model.getRecipeSelected(docId: documentId)
放在我的viewDidLoad()
中来确认它是有效的。问题似乎是它在分段之前没有检索/传递数据到View Controller 2。
编辑:我也尝试过以下操作,但没有成功
1.为我的模型添加了一个完成处理程序,并在prepare函数中完成所有操作
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MealPlanToSegmentedControl" {
guard let destination = segue.destination as? UINavigationController else {
return
}
guard let finalDestination = destination.viewControllers.first as? SegmentedControlViewController else {
return
}
if let indexPath = tableView.indexPathForSelectedRow {
let documentID = recipeDocIdArray[indexPath.row]
finalDestination.passedDocID = documentID
model.getRecipeSelected(docId: documentID) {
print("(entireRecipe)") // FIXME: SEGUE HAPPENS BEFORE entireRecipe IS ASSIGNED ANY DATA
finalDestination.entireRecipe = entireRecipe
}
}
}
}
2.在我的模型中添加了一个完成处理程序,并使用didSelectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let documentID = recipeDocIdArray[indexPath.row]
model.getRecipeSelected(docId: documentID) {
self.performSegue(withIdentifier: "MealPlanToSegmentedControl", sender: Any?.self)
}
}
- 在VC1中添加一个属性,该属性将存储您的配方
- 为VC1
didReceiveRecipe(recipe:)
创建一个委托,它将更新配方属性并将您的模型设置为VC1的委托。更新配方后,现在也可以调用performSegue
,当您达到调用prepare(for:sender:)
的点时,您肯定会有可用的配方 - 在
didSelectRow
委托方法中,要求模型获取配方,然后调用委托方法