协议委托模式不通知视图控制器

Protocol-Delegate pattern not notifying View Controller

我的 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")
    }
}

我从这个模式中遗漏了什么吗?我没能注意到我看过的文章有什么不同。

所以我测试了你的代码并模拟了类似的东西

import UIKit

protocol ProtocolModel {
    func wasDataSavedSuccessfully(dataSavedSuccessfully:Bool)
}

class Model {
    
    var delegate:ProtocolModel?
    
    // I use this timer for simulate that firebase store data every 3 seconds for example
    var timer: Timer?
    
    func createUserAddedRecipe(
        docId:String) {
            
            timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { _ in
                self.delegate?.wasDataSavedSuccessfully(dataSavedSuccessfully: true)
            })
        }
}

class NavigationController: UINavigationController {
    
    var model = Model()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        model.delegate = self
        // Call this method to register for network notification
        model.createUserAddedRecipe(docId: "exampleId")
    }
}

extension NavigationController: ProtocolModel {
    func wasDataSavedSuccessfully(dataSavedSuccessfully: Bool) {
        print(#function)
    }
}

因此您可以看到如下图所示的结果,我的委托更新控制器符合该协议。