【问题标题】:Swift ViewModel implementation with Array使用数组的 Swift ViewModel 实现
【发布时间】:2017-01-15 16:01:36
【问题描述】:

这段代码是 MVVM 架构的正确实现吗?我想知道是否可以将下载的数组保存在私有属性中以供将来在 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()
}

【问题讨论】:

    标签: ios swift mvvm


    【解决方案1】:

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

    【讨论】:

    • 我也在寻找答案。 IMO 有趣的一点是,您必须从 ViewController 调用 getStop(atIndex:)。这会破坏 MVVM 模式吗?因为 VC 必须知道模型(在这种情况下停止)。有一个函数 getStopParameter(atIndex:) -> Any 更好吗?而是返回 self.stops[index].parameter?
    猜你喜欢
    • 2016-01-08
    • 1970-01-01
    • 2014-11-18
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    相关资源
    最近更新 更多