在过去的几个小时里,我一直在玩代码,我想我已经想出了一个很好的方法。我不知道这是否是预期的方式,或者它是否是正确的 MVVM,但它似乎工作并且实际上非常方便。
我将在下面发布一个完整的工作示例,供任何人试用。它应该开箱即用。
这里有一些想法(可能完全是垃圾,我对那些东西一无所知。如果我错了,请纠正我:))
我认为这view models
可能不应该包含或保存模型中的任何实际数据。这样做将有效地创建已保存在model layer
. 将数据存储在多个位置会导致您在更改任何内容时必须考虑的各种同步和更新问题。我尝试的所有东西最终都变成了一大块难以理解的丑陋代码。
对模型内部的数据结构使用类并不能很好地工作,因为它使检测更改变得更加麻烦(更改属性不会更改对象)。因此,我改为Character
a 类。struct
我花了几个小时试图弄清楚如何model layer
在view model
. 我尝试设置自定义发布者、跟踪任何更改并相应更新视图模型的自定义订阅者,我考虑让model
订阅者view model
以及建立双向通信等。没有任何结果。感觉很不自然。但事情是这样的:模型不必与视图模型通信。事实上,我认为根本不应该。这可能就是 MVVM 的意义所在。raywenderlich.com上的 MVVM 教程中显示的可视化也显示了这一点:
(来源:https ://www.raywenderlich.com/4161005-mvvm-with-combine-tutorial-for-ios )
那是一种单向连接。视图模型从模型中读取数据,并可能对数据进行更改,仅此而已。
因此,我没有model
告诉view model
任何更改,而是通过将模型view
设为. 每次更改时,都会重新计算视图,该视图调用. 然而, 只是从模型中获取当前数据(因为它只访问并且从不保存它们)并将其提供给视图。视图模型根本不需要知道模型是否已更新。没关系。model
ObservableObject
view model
view model
考虑到这一点,使示例工作并不难。
这是演示所有内容的示例应用程序。它只是显示所有字符的列表,同时显示显示单个字符的第二个视图。
进行更改时,两个视图都会同步。

import SwiftUI
import Combine
/// The model layer.
/// It's also an Observable object so that swiftUI can easily detect changes to it that trigger any active views to redraw.
class MyGame: ObservableObject {
/// A data object. It should be a struct so that changes can be detected very easily.
struct Character: Equatable, Identifiable {
var id: String { return name }
let name: String
var strength: Int
static func ==(lhs: Character, rhs: Character) -> Bool {
lhs.name == rhs.name && lhs.strength == rhs.strength
}
/// Placeholder character used when some data is not available for some reason.
public static var placeholder: Character {
return Character(name: "Placeholder", strength: 301)
}
}
/// Array containing all the game's characters.
/// Private setter to prevent uncontrolled changes from outside.
@Published public private(set) var characters: [Character]
init(characters: [Character]) {
self.characters = characters
}
public func update(_ character: Character) {
characters = characters.map { $0.name == character.name ? character : $0 }
}
}
/// A View that lists all characters in the game.
struct CharacterList: View {
/// The view model for CharacterList.
class ViewModel: ObservableObject {
/// The Publisher that SwiftUI uses to track changes to the view model.
/// In this example app, you don't need that but in general, you probably have stuff in the view model that can change.
let objectWillChange = PassthroughSubject<Void, Never>()
/// Reference to the game (the model).
private var game: MyGame
/// The characters that the CharacterList view should display.
/// Important is that the view model should not save any actual data. The model is the "source of truth" and the view model
/// simply accesses the data and prepares it for the view if necessary.
public var characters: [MyGame.Character] {
return game.characters
}
init(game: MyGame) {
self.game = game
}
}
@ObservedObject var viewModel: ViewModel
// Tracks what character has been selected by the user. Not important,
// just a mechanism to demonstrate updating the model via tapping on a button
@Binding var selectedCharacter: MyGame.Character?
var body: some View {
List {
ForEach(viewModel.characters) { character in
Button(action: {
self.selectedCharacter = character
}) {
HStack {
ZStack(alignment: .center) {
Circle()
.frame(width: 60, height: 40)
.foregroundColor(Color(UIColor.secondarySystemBackground))
Text("\(character.strength)")
}
VStack(alignment: .leading) {
Text("Character").font(.caption)
Text(character.name).bold()
}
Spacer()
}
}
.foregroundColor(Color.primary)
}
}
}
}
/// Detail view.
struct CharacterDetail: View {
/// The view model for CharacterDetail.
/// This is intentionally only slightly different to the view model of CharacterList to justify a separate view model class.
class ViewModel: ObservableObject {
/// The Publisher that SwiftUI uses to track changes to the view model.
/// In this example app, you don't need that but in general, you probably have stuff in the view model that can change.
let objectWillChange = PassthroughSubject<Void, Never>()
/// Reference to the game (the model).
private var game: MyGame
/// The id of a character (the name, in this case)
private var characterId: String
/// The characters that the CharacterList view should display.
/// This does not have a `didSet { objectWillChange.send() }` observer.
public var character: MyGame.Character {
game.characters.first(where: { $0.name == characterId }) ?? MyGame.Character.placeholder
}
init(game: MyGame, characterId: String) {
self.game = game
self.characterId = characterId
}
/// Increases the character's strength by one and updates the game accordingly.
/// - **Important**: If the view model saved its own copy of the model's data, this would be the point
/// where everything goes out of sync. Thus, we're using the methods provided by the model to let it modify its own data.
public func increaseCharacterStrength() {
// Grab current character and change it
var character = self.character
character.strength += 1
// Tell the model to update the character
game.update(character)
}
}
@ObservedObject var viewModel: ViewModel
var body: some View {
ZStack(alignment: .center) {
RoundedRectangle(cornerRadius: 25, style: .continuous)
.padding()
.foregroundColor(Color(UIColor.secondarySystemBackground))
VStack {
Text(viewModel.character.name)
.font(.headline)
Button(action: {
self.viewModel.increaseCharacterStrength()
}) {
ZStack(alignment: .center) {
Circle()
.frame(width: 80, height: 80)
.foregroundColor(Color(UIColor.tertiarySystemBackground))
Text("\(viewModel.character.strength)").font(.largeTitle).bold()
}.padding()
}
Text("Tap on circle\nto increase number")
.font(.caption)
.lineLimit(2)
.multilineTextAlignment(.center)
}
}
}
}
struct WrapperView: View {
/// Treat the model layer as an observable object and inject it into the view.
/// In this case, I used @EnvironmentObject but you can also use @ObservedObject. Doesn't really matter.
/// I just wanted to separate this model layer from everything else, so why not have it be an environment object?
@EnvironmentObject var game: MyGame
/// The character that the detail view should display. Is nil if no character is selected.
@State var showDetailCharacter: MyGame.Character? = nil
var body: some View {
NavigationView {
VStack(alignment: .leading) {
Text("Tap on a character to increase its number")
.padding(.horizontal, nil)
.font(.caption)
.lineLimit(2)
CharacterList(viewModel: CharacterList.ViewModel(game: game), selectedCharacter: $showDetailCharacter)
if showDetailCharacter != nil {
CharacterDetail(viewModel: CharacterDetail.ViewModel(game: game, characterId: showDetailCharacter!.name))
.frame(height: 300)
}
}
.navigationBarTitle("Testing MVVM")
}
}
}
struct WrapperView_Previews: PreviewProvider {
static var previews: some View {
WrapperView()
.environmentObject(MyGame(characters: previewCharacters()))
.previewDevice(PreviewDevice(rawValue: "iPhone XS"))
}
static func previewCharacters() -> [MyGame.Character] {
let character1 = MyGame.Character(name: "Bob", strength: 1)
let character2 = MyGame.Character(name: "Alice", strength: 42)
let character3 = MyGame.Character(name: "Leonie", strength: 58)
let character4 = MyGame.Character(name: "Jeff", strength: 95)
return [character1, character2, character3, character4]
}
}