Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ObservedObject란? #2

Open
JJinuk opened this issue May 14, 2023 · 0 comments
Open

ObservedObject란? #2

JJinuk opened this issue May 14, 2023 · 0 comments
Labels
🎨SwiftUI SwiftUI 관련 내용

Comments

@JJinuk
Copy link
Owner

JJinuk commented May 14, 2023

ObservedObject?

  • observable 객체를 구독하는 property wrapper
    • observavle 객체가 변경되면 뷰에 업데이트 시켜주는 기능

@ObservedObject 사용 방법

  • ObservableObject를 준수하는 모델을 만들고, 그 모델에서 값이 변경되면 뷰에 반영하기 위해 사용
  • ObservavleObject를 준수하는 인스턴스를 참조하기 위해 @ObservedObject로 선언하여 참조

ex) @ObservedObject 사용하여 MVVM 패턴 만들기

  • 모델 정의(ObservableObject를 준수)
    • ObservableObject는 class 형태만 가능(struct가 아님)
final class MyViewModel: ObservableObject {
  @Published var isOn = false
  
  func toggle() {
    isOn.toggle()
  }
}

🔼위 모델의 인스턴스를 @ObservedObject로 참조

struct ContentView: View {
  @ObservedObject var viewModel1 = MyViewModel()
  
  var body: some View {
    VStack {
      Button(viewModel1.isOn ? "on" : "off") {
        viewModel1.toggle()
      }
    }
  }
}

참고: https://ios-development.tistory.com/1160
https://developer.apple.com/documentation/swiftui/observedobject

@JJinuk JJinuk added the 🎨SwiftUI SwiftUI 관련 내용 label May 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🎨SwiftUI SwiftUI 관련 내용
Projects
None yet
Development

No branches or pull requests

1 participant