【发布时间】:2022-02-19 06:46:09
【问题描述】:
我的Model 将数据保存到 Firestore。保存该数据后,我希望它提醒我的ViewController,以便可以调用函数。但是,没有任何东西传递给我的ViewController。
这是我的Model:
protocol ProtocolModel {
func wasDataSavedSuccessfully(dataSavedSuccessfully:Bool)
}
class Model {
var delegate:ProtocolModel?
func createUserAddedRecipe(
docId:String,
completion: @escaping (Recipe?) -> Void) {
let db = Firestore.firestore()
do {
try db.collection("userFavourites").document(currentUserId).collection("userRecipes").document(docId).setData(from: recipe) { (error) in
print("Data Saved Successfully") // THIS OUTPUTS TO THE CONSOLE
// Notify delegate that data was saved to Firestore
self.delegate?.wasDataSavedSuccessfully(dataSavedSuccessfully: true)
}
}
catch {
print("Error \(error)")
}
}
}
print("Data Saved Successfully") 输出到控制台,但它下面的委托方法没有被调用。
这是我的ViewController:
class ViewController: UIViewController {
private var model = Model()
override func viewDidLoad() {
super.viewDidLoad()
model.delegate = self
}
}
extension ViewController: ProtocolModel {
func wasDataSavedSuccessfully(dataSavedSuccessfully: Bool) {
if dataSavedSuccessfully == true {
print("Result is true.")
}
else {
print("Result is false.")
}
print("Protocol-Delegate Pattern Works")
}
}
这个模式有什么我遗漏的吗?我没有注意到我所评论的文章有什么不同。
【问题讨论】:
-
您不应该在
catch中调用您的委托方法吗?您还应该将该委托属性设为weak,但这是一个单独的主题。 -
你打电话给
createUserAddedRecipe。我建议将let db = Firestore.firestore()存储为模型的属性 -
不知道你在哪里调用 createUserAddedRecipe 方法?
-
我测试了类似你的代码的东西,一切都像魅力一样,如果你愿意,我可以与你分享
-
@RezaKhonsari 我很想看看你的例子!
标签: ios swift model-view-controller delegates protocols