SwiftUI의 ObservableObject를 이용하여 데이터 모델과 뷰를 쉽게 바인딩하는 방법

ObservableObject를 사용하려면 구현해야 하는 3가지

Munok Kim
2 min readJul 26, 2020
Photo by Sergey Semin on Unsplash

ObservableObject를 사용할 때에는 다음 3가지를 모두 구현하여야 합니다.

protocol ObservableObject

클래스 프로토콜 ObservableObject를 클래스에 채택하면 해당 클래스의 인스턴스를 관찰하고 있다가 값이 변경되면 뷰를 업데이트 합니다.

@Published

ObservableObject에서 속성을 선언할 때 사용하는 PropertyWrapper입니다. @Published로 선언된 속성이 ObservableObject에 포함되어 있다면 해당 속성이 업데이트 될 때마다 뷰를 업데이트 합니다.

@ObservedObject

ObservableObject를 구독하고 값이 업데이트 될 때 마다 뷰를 갱신하는 PropertyWrapper입니다.

이를 토대로 사용자에게 텍스트를 입력받아 ObservableObject@Published 속성에 값을 추가하고 @ObservedObject 속성으로 구독하여 List에 업데이트하는 예제를 만들었습니다.

다음은 코드 전문입니다. 이처럼 SwiftUI에서 ObservableObject를 이용하여 매우 간단하게 Object와 뷰를 바인딩 할 수 있습니다.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Munok Kim
Munok Kim

Written by Munok Kim

앱 깎는 장인이 되고 싶은 iOS 개발자입니다

No responses yet

Write a response