简体   繁体   中英

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

I'm on Xcode 10.2.1 with swift 5

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

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. 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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