我正在使用 swift 创建一个应用程序。该应用程序从类 WeatherDataModel 中的 openweathermap.com api 获取天气,然后在加载数据时,模型要求 viewController 更新数据
我在 Xcode 10.2.1 上使用 swift 5
我创建了一个在模型中调用的协议(protocol)来更新数据,但是 updateDisplayDelegate?.updateWeatherDataOnDisplay() 始终为 nil,即使我从控制台中的 JSON 获取数据,它也不会在屏幕上更新
class WeatherDataModel {
var updateDisplayDelegate: ProtocolUpdateDisplay?
func updateWeaterData(json : JSON) {
updateDisplayDelegate?.updateWeatherDataOnDisplay()
}
}
public protocol ProtocolUpdateDisplay {
func updateWeatherDataOnDisplay()
}
class MainViewController: UIViewController {
let weatherDataModel = WeatherDataModel()
override func viewDidLoad() {
super.viewDidLoad()
weatherDataModel.updateDisplayDelegate = self
}
extension MainViewController: ProtocolUpdateDisplay {
func updateWeatherDataOnDisplay() {
cityLabel.text = weatherDataModel.city
tempLabel.text = weatherDataModel.temperature
weatherIcon.image = UIImage(named: weatherDataModel.weatherIconName)
}
}
最佳答案
你不应该为模型使用delegation
模式。考虑使用通知:
func updateWeaterData(json : JSON) {
NotificationCenter.default.post(Notification(name: Notification.Name("WeatherDidUpdate")))
}
并在您想要响应此通知的任何 Controller 中观察:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(updateWeatherDataOnDisplay(_:)), name: Notification.Name("WeatherDidUpdate"), object: nil)
}
@objc func updateWeatherDataOnDisplay(_ notification: Notification) {
cityLabel.text = weatherDataModel.city
tempLabel.text = weatherDataModel.temperature
weatherIcon.image = UIImage(named: weatherDataModel.weatherIconName)
}
最后移除观察者:
deinit {
NotificationCenter.default.removeObserver(self)
}
关于swift - 使用 SWIFT 从 MVC 中的 Controller 更新 viewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56407170/