swift - 使用 SWIFT 从 MVC 中的 Controller 更新 viewController

标签 swift model-view-controller delegates protocols

我正在使用 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/

相关文章:

swift - 在 Swift 的循环中向下计数的最佳方法是什么

swift - 我们可以退出一个函数(不是从应用程序)或者甚至使用跳转到特定行吗?

java - MVC - 当内容类型是自定义的(不是应用程序/json)时接受 JSON

c# - 使用 MulticastDelegate 作为参数同时避免 DynamicInvoke

iphone - 如何使用自己的委托(delegate)方法添加 subview ?

ios - RxSwift,链相关下载返回相同的 Observable 类型

ios - 我的应用程序崩溃了,并显示该类不符合使用swift编写的key tableView的键值编码

javascript - 通过软件包安装程序安装时,Knockout 未定义

c# - 使用 TypedFactoryFacility 错误吗?

c# - 当方法包含 'ref' 参数时创建委托(delegate)的最简单方法