ios - 使用 Array 实现 Swift ViewModel

标签 ios swift mvvm

这段代码是MVVM架构的正确实现吗?我想知道是否可以将下载的数组保留在私有(private)属性中以供将来在 TableView 中使用,或者我应该不惜一切代价避免这种情况?

代码:

import Foundation

class StopsViewModel {

    weak var delegate: StopsViewModelDelegate?
    private let dbService: DatabaseService
    private var stops = [Stop]()

    init(withDbService dbService: DatabaseService) {
        self.dbService = dbService
    }

    func loadStops() {
        dbService.getStops(completion: { [weak self] stops in
            self?.stops = stops
            self?.delegate?.getStopsCallFinished()
        })
    }

    func getStop(atIndex index: Int) -> Stop {
        return self.stops[index]
    }

    func getRowCount() -> Int {
        return self.stops.count
    }

    func getSectionsCount() -> Int {
        return 1
    }
}

protocol StopsViewModelDelegate: class {
    func getStopsCallFinished()
}

最佳答案

在与一些工作中的高级开发人员交谈后,他们告诉我,这是他们通常采取的方式。由于将数组保留在 View 模型中不会破坏 MVVM 模式,因此可以非常轻松地重用数据并清除数据服务以保留其他字段(使其更可重用)。

关于ios - 使用 Array 实现 Swift ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41663142/

相关文章:

ios - didUpdateLocations 未被调用

ios - 点击按钮时创建 collectionView

wpf - 从另一个ViewModel引发MVVM属性的最佳方法是什么?

c# - 列表框不显示特定对象的值(数据绑定(bind))

ios - 导航 Controller 后退按钮标题显示上一个标题

ios - PushSharp 未识别 APN 生产证书

ios - 即使视口(viewport)元标记中的分辨率宽度为 1536,ipad 3 设备宽度是否始终为 768?

ios - 模块 'SocketIO' 未使用库进化支持进行编译;使用它意味着无法保证框架的二进制兼容性

ios - 如何从 TabbarController 继续查看 Controller ?

WPF MVVM 绑定(bind) ContentConrol 的 ContentTemplate 的 StaticResource