模型返回数据后,didSelectRowAt中未分配变量



我有以下Model,它将数据返回到我的View Controller:

func getRecipeSelected(docId: String, completionHandler: @escaping () -> Void) {
db.collection("recipes").document(docId).getDocument { document, error in
if let error = error as NSError? {
}
else {
if let document = document {
do {
self.recipe = try document.data(as: Recipe.self)

let recipeFromFirestore = Recipe(
id: docId,
title: self.recipe!.title ?? "",
analyzedInstructions: self.recipe!.analyzedInstructions!)

DispatchQueue.main.async {
self.delegateSpecificRecipe?.recipeSpecificRetrieved(recipeSelected: recipeFromFirestore)
}
}
catch {
print("Error: (error)")
}
}
}
}
completionHandler()
}

这是在我的View Controller:中

var entireRecipe: Recipe? = nil
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

documentID = recipeDocIdArray[indexPath.row]

model.getRecipeSelected(docId: documentID) {
print("ISSUE HERE: (self.entireRecipe)") // FIXME: THIS IS NIL THE FIRST TIME IT IS CALLED
}
}

我的问题是entireRecipe没有在我的视图控制器中的完成处理程序中分配来自model的数据。如果我要在第二次的时间点击单元格,那么第一次点击的数据将在该完成处理程序中分配。

如何在第一次点击时将返回的数据分配给该范围内的entireRecipe

您正在调用委托方法,而不是调用completionHandler。您还在异步块中调用委托方法,该方法在completionHandler之后调用。不需要一排两个。您可以使用类似于的completionHandler

func getRecipeSelected(docId: String, completionHandler: @escaping (Recipe?) -> Void) {
db.collection("recipes").document(docId).getDocument { document, error in
if let error = error as NSError? {
}
else {
if let document = document {
do {
self.recipe = try document.data(as: Recipe.self)

let recipeFromFirestore = Recipe(
id: docId,
title: self.recipe!.title ?? "",
analyzedInstructions: self.recipe!.analyzedInstructions!)

completionHandler(recipeFromFirestore)
}
catch {
print("Error: (error)")
completionHandler(nil)
}
}
}
}
}
var entireRecipe: Recipe?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

documentID = recipeDocIdArray[indexPath.row]

model.getRecipeSelected(docId: documentID) { [weak self] model in
self?.entireRecipe = model
}
}

最新更新