简体   繁体   English

委托不调用Swift协议方法

[英]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. 由于某种原因,未在主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)
    }
}

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“: 这里正确应用了委托模式,但有一件事可能会出错:在主View Controller中,您实例化一个新的Parser对象并将其存储在“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) 这意味着:如果您的Parser()类的实例跳转到(确保使用调试器,如果实际上确实如此)

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. 如果这是问题,您可以考虑并插入以便能够直接与此特定Parser()类进行通信。 Hope this helps. 希望这可以帮助。

You can also edit this line: 您也可以编辑此行:

from: 从:

dataSource.delegate = self
dataSourse.loadAndParse()

to: 至:

dataSource.delegate = self
dataSource.loadAndParse()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM