[英]Update the viewController from the controller in MVC with SWIFT
I'm creating an app with swift. 我正在快速创建一个应用程序。 The app get weather from openweathermap.com api in the class WeatherDataModel then when the data are loaded, the model ask the viewController to update the datas
该应用程序从WeatherWeatherModel类的openweathermap.com api获取天气,然后在加载数据时,模型要求viewController更新数据
I'm on Xcode 10.2.1 with swift 5 我正在使用Swift 5的Xcode 10.2.1
I've create a protocol called in the model to update the data but the updateDisplayDelegate?.updateWeatherDataOnDisplay() is always nil and even if I get the data from the JSON in the console it won't update on the screen 我已经在模型中创建了一个协议来更新数据,但是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)
}
}
You should not use delegation
pattern for model. 您不应将
delegation
模式用于模型。 Consider using notification: 考虑使用通知:
func updateWeaterData(json : JSON) {
NotificationCenter.default.post(Notification(name: Notification.Name("WeatherDidUpdate")))
}
and observe in any controller you want to respond to this notification: 并在您要响应此通知的任何控制器中进行观察:
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)
}
and remove observer at last: 并最后删除观察者:
deinit {
NotificationCenter.default.removeObserver(self)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.