Create ViewModel with @StateObject and @EnvironmentObject for MVVM | SwiftUI Map App #2
@StateObject
을 통해 특정 뷰 모델 관찰@EnvrionmentObject
구현import Foundation
@MainActor
final class LocationsViewModel: ObservableObject {
@Published var locations: [LocationModel]
init(locations: [LocationModel] = LocationModel.stubs) {
self.locations = locations
}
}
locations
데이터가 퍼블리셔이므로 해당 데이터가 업데이트될 때 해당 데이터를 통한 UI 업데이트import SwiftUI
@main
struct MapCloneApp: App {
@StateObject private var viewModel = LocationsViewModel()
var body: some Scene {
WindowGroup {
LocationsView()
.environmentObject(viewModel)
}
}
}
EnvironmentObject
를 통해 뷰 모델 연결import SwiftUI
struct LocationsView: View {
@EnvironmentObject private var viewModel: LocationsViewModel
var body: some View {
List {
ForEach(viewModel.locations) { location in
Text(location.name)
}
}
}
}