ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • SwiftUI ) StateObject Apple Documentation 번역
    SwiftUI/Basic Property Wrappers 2021. 10. 5. 19:44

    StateObject 

    Observable Object 의 instance 를 만들 때 사용하는 Property Wrapper ( iOS 14 이상에서만 가능.. 아마도 SwiftUI 2.0 이상?)

    Observed Object ( Binding Object 라고 생각하면 편해요. (State <-> Binding 은 두 views 사이에서만! ) 
    class도  Object가 될 수 있음. 단, ObservableObject를 conform해야함.  (class CustomClass: ObservableObject) 
    class 라서 여러 properties, methods 를 가질 수 있고,
    각 properties 는 선택적으로 @Published wrapper 를 씌울 수 있음.  이게 씌인 것들은 변할 때마다 views에 바로바로 반영)

     

     

     

    세개 이상의 Views 에서 데이터를 공유하고자 할 때는, State 대신 StateObject 로 써주세요. 

     

    View, App, Scene 에서 state object 를 만들려면  (state object : view struct 내에서 변할 수 있음 , state 아닌 경우 에러발생)

     

    1. 앞에 @StateObject 을 쓰고

    2. ObservableObject protocol 을 conform하는 value 를 할당해주세요. 

    @StateObject var model = DataModel()

     

     

    SwiftUI 는 각 structure instance (object 를 갖는 structure)  마다 단 한번만 object 의 instance 를 생성합니다. 

    Observable object 중 published properties 가 변할 때, 해당 properties 가 UI 의 재료로 쓰이는 View들은 자동 update 됩니다. 

    Text(model.title) // Updates the view any time `title` changes.

    ObservedObject 를 갖는 property 에 StateObject 를 넘겨줄 수 있어요. 또는 view hierarchy 의 environment에 추가해줄 수 있습니다. environmentObject(_:) 를 사용해서요.

    ContentView().environmentObject(model) 
    // ContentView 의 ObservedObject 에 model(State Object) 을 넘김.

     

     

    만약 위 예시 코드에서처럼 environment object 를 생성하면, ContentView 나 ContentView 의 descendant views 에서 EnvironmentObject 를 이용해서 해당 object 를 읽을 수 있습니다.

    @EnvironmentObject var model: DataModel

    $ (연산자) 를 이용해서 State Object 의 properties 중 하나와 Binding 을 시킬 수 있습니다. Binding 을 통해 Object의 properties 중 하나와 양방향으로 데이터를 주고받을 수 있어요. 

     

    예를 들면, Toggle 이 isEnabled 변수를 control 하게 할 수 있습니다. 

    Toggle("Enabled", isOn: $model.isEnabled)

     

    TODO : 예시 코드 생성 (Simulator 에서 돌아가도록) 후 github 공유

     

     

    역시.. Apple Documentation 이 최고입니다.. 

    출처: https://developer.apple.com/documentation/swiftui/stateobject

Designed by Tistory.