
MVVM: Model - View - ViewModel
MVVM은 소프트웨어 아키텍처 패턴 중 하나로 유지보수와 테스트를 용이하게 하고 코드의 재사용성을 높이는 데 목적이 있습니다. Swift에서 많이 사용되는 패턴 중 하나입니다.
각 구조는 다음과 같은 역할을 합니다.
struct나 class로 표현class로 표현즉 Model은 데이터를 담당하고 ViewModel은 이 데이터를 가공하여 View에 전달하면 View가 가공된 데이터를 보여주는 구조입니다.
예를 들어 사용자가 알림설정을 토글로 on/off 할 수 있는 기능을 MVVM 패턴을 사용하여 만들어보겠습니다.
class NotificationManager {
static let shared = NotificationManager()
// 싱글톤 생성
private init() {}
// 초기화
var isNotificationEnabled: Bool {
get {
return UserDefaults.standard.bool(forKey: "isNotificationEnabled")
}
set {
UserDefaults.standard.set(newValue, forKey: "isNotificationEnabled")
}
// 알림설정 데이터를 UserDefaults에 저장하여 전역적으로 관리
}
}
NotificationManager은 알림 설정을 관리하는 모델입니다.
isNotificationEnabled은 UserDefaults를 사용하여 알림 설정을 저장하고 불러오는 프로퍼티입니다.
저는 싱글톤으로 구성하였습니다. 싱글톤으로 구현하면, 어디서든 하나의 인스턴스를 공유하여 사용할 수 있습니다.
class NotificationViewModel {
private let notificationManager: NotificationManager
init(notificationManager: NotificationManager = NotificationManager.shared) {
self.notificationManager = notificationManager
}
var isNotificationEnabled: Bool {
return notificationManager.isNotificationEnabled
}
func toggleNotification() {
notificationManager.isNotificationEnabled.toggle()
}
}
NotificationViewModel은 뷰와 모델 간의 중간 매개체로, 화면에 필요한 데이터를 제공하고 사용자의 알림 설정 변경을 처리합니다.
isNotificationEnabled는 모델에서 가져온 알림 설정을 뷰에 표시하기 위한 프로퍼티입니다.
toggleNotification 함수는 알림 설정을 토글하는 메서드입니다.
import SwiftUI
struct NotificationView: View {
@ObservedObject var viewModel: NotificationViewModel
var body: some View {
VStack {
Text("Notification Settings")
.font(.title)
Toggle("Enable Notifications", isOn: $viewModel.isNotificationEnabled)
.padding()
.onChange(of: viewModel.isNotificationEnabled) { newValue in
viewModel.toggleNotification()
}
// 토글이 변경될 때 ViewModel의 toggleNotification 함수 호출
Spacer()
}
.padding()
}
}
struct NotificationView_Previews: PreviewProvider {
static var previews: some View {
NotificationView(viewModel: NotificationViewModel())
}
}
@ObservedObject 속성 래퍼를 사용하여 NotificationViewModel을 감시합니다. 이를 통해 ViewModel이 변경될 때 뷰가 자동으로 업데이트됩니다.
Toggle은 알림 설정을 토글하는 데 사용되며, onChange 클로저를 사용하여 토글 값이 변경될 때마다 ViewModel의 toggleNotification 함수를 호출합니다.