gpt4 book ai didi

ios - MVP 架构模式示例。 swift

转载 作者:行者123 更新时间:2023-11-28 11:38:15 24 4
gpt4 key购买 nike

我想学习经典的 MVP 架构模式,为此尝试在 Swift 上实现天气应用程序。我从理论上了解了它应该如何工作,但实际上停留在基本理解上。现在我有一个模型:

型号

class WeatherModel: Codable {
var name: String?
var main: Main?
}

class Main: Codable {
var temperature: Float?
var pressure: Int?
var humidity: Int?
private enum CodingKeys: String, CodingKey {
case temperature = "temp"
case pressure
case humidity
}

查看

final class WeatherViewController: UIViewController {
@IBOutlet weak var cityTextField: UITextField!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var pressureLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!

private var presenter: WeatherPresenter!

// MARK: - Lifecycle

override func viewDidLoad() {
super.viewDidLoad()
presenter = WeatherPresenter()
cityTextField.delegate = self
presenter.delegate = self

}

@IBAction func buttonClicked(_ sender: Any) {
let city = cityTextField.text
if let city = city {
presenter.loadWeatherFor(city: city)
}
}
}

extension WeatherViewController: WeatherPresenterProtocol {

// MARK: - WeatherPresenterProtocol

func showWeather(data: WeatherModel) {
if let temperature = data.main?.temperature {
self.temperatureLabel.text = String(temperature)
}
if let pressure = data.main?.pressure {
self.pressureLabel.text = Constants.pressure + String(pressure)
}
if let humidity = data.main?.humidity {
self.humidityLabel.text = Constants.humidity + String(humidity)
}
}
}

演示者

protocol WeatherPresenterProtocol: class {
func showWeather(data: WeatherModel) // ?
}

final class WeatherPresenter {
var model: WeatherModel!
weak var delegate: WeatherPresenterProtocol?

func loadWeatherFor(city: String) {
Network.shared.getWeather(city) { [weak self] (weather, error) in
DispatchQueue.main.async {
self?.model = weather
}
}
}
}

Presenter 中,我从网络服务接收数据,但我无法理解如何使用此数据更新 View(如何在 Presenter< 中实现协议(protocol)) 因为 View 不应该知道模型,但在我的例子中它会知道(任何实现经典 MVP 的想法都将不胜感激!

第二个问题:如何在 Presenter 中实现协议(protocol)以获取 Model(如我从 https://www.youtube.com/watch?v=qzTeyxIW_ow 中截取的图片所示) enter image description here

最佳答案

改变

func showWeather(data: WeatherModel)

func showWeather(temperature: String, pressure: String, humidity: String)

将这些字符串的构造从View移到Presenter。这样,View 仍然不知道模型。

Presenter 不应直接与完整 View 对话,而应仅与协议(protocol)对话。

关于ios - MVP 架构模式示例。 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54497421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com