Search code examples
iosswiftdelegation

Swift protocol method is not being called by the delegate


For some reason the delegate method is not being called in the main View Controller. I was looking for another answers here, but non of them were helpful for me. Am I missing something here? (I shortened my original code for simplicity sake)

Main View Controller:

class VC: ParserDelegate {
    var dataSource = Parser()

    override func viewDidLoad() {
        super.viewDidLoad()

        dataSource.delegate = self
        dataSourse.loadAndParse()
    }

    func didReceiveDataUpdates(store: [WeatherModel]) {
        print("Delegate method triggered.")
    }

}

Protocol:

protocol ParserDelegate: class {
    func didReceiveDataUpdates(store: [WeatherModel])
}

My delegate class:

class Parser {
    weak var delegate: ParserDelegate?

    func loadAndParse() {
        var store = [WeatherModel]()
        // Doing something

        delegate?.didReceiveDataUpdates(store: store)
    }
}

Solution

  • The delegate pattern is being applied correctly here, but one thing that might go wrong here: In your main View Controller you are instantiating a new Parser object and store it in „dataSource“:

    var dataSource = Parser()
    

    And when setting your main View Controller as its delegate

    dataSource.delegate = self
    

    your main View Controller gets notified as the delegate of this new instance you just created. That means: If an instance of your Parser() class jumps into (assure with debugger, if it actually does)

    loadAndParse()
    

    it might be another object and so this parser object has no actual delegate. If this is the issue here, you might consider and outlet in order to be able to talk to this specific Parser() class directly. Hope this helps.