SwiftUI @ 뭘까 ?

조영민·2022년 6월 12일
0

SwiftUI 공부를 하던 와중 @표시가 너무 많아서 헷갈렸다.
combine도 공부해야하는데 SwiftUI도 어렵다. ㅜ

@state, @observedObject, @enviormentObject

한번 알아보자.

@state

프로퍼티 래퍼다.

Don’t initialize a state property of a view at the point in the view hierarchy where you instantiate the view, because this can conflict with the storage management that SwiftUI provides. To avoid this, always declare state as private, and place it in the highest view in the view hierarchy that needs access to the value. Then share the state with any child views that also need access, either directly for read-only access, or as a binding for read-write access.
You can safely mutate state properties from any thread.

일단 읽자.
1. private으로 하라고 한다.

If you pass a state property to a child view, SwiftUI updates the child any time the value changes in the parent, but the child can’t modify the value. To enable the child view to modify the stored value, pass a Binding instead. You can get a binding to a state value by accessing the state’s projectedValue, which you get by prefixing the property name with a dollar sign ($).

state property를 child View에 넘기면 state 바뀔때 업데이트를 해준답니다 ! 아하
하지만 자식은 건들 수 없다는거 !
$로 이제 자식이 바꿀 수 있는거임 바인딩해서

@ObservedObject

구현부의 @published 를 사용해서 데이터가 변경된 걸 알 수 있음

데이터 스토리지에 적어주면 변화를 감지하고 View를 reload해준다고한다.

추측 ... 추측... 이지만 ViewModel 에 적어주면 될 거 같다.

근데 View에 인스턴스 생성해주지 말란다.

참고: https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-observedobject-to-manage-state-from-external-objects

@EnviormentObject

이건 모든 View가 바라보는 object다.

아까 위에서 @state 해줄때 자식 어쩌고 한걸로 보아 저건 자식만 되는데 이건 다 되나보다.

@published로 감싸준 프로퍼티를 앱 전역에서 사용 할 수 있다.

@StateObject

  • iOS 14.0

A property wrapper type that instantiates an observable object.

이 친구는 ObservedObject가 인스턴스화 되어있는 친구인데 View가 초기화되도 별개의 객체로 관리된다고 한다.

애플이 추천하는 StateObject와 ObservedObject의 사용법은 Observable Object를 처음 초기화할 때는 StateObject를 사용하고, 이미 객체화된 것을 넘겨 받을 때 ObservedObject의 사용을 추천하고 있다.

출처: https://medium.com/hcleedev/swift-observedobject%EC%99%80-stateobject-4f851ed9ef0d

//TODO: @Binding
세줄 요약:

  1. @published , 프로퍼티 래퍼 공부 필요
  2. 스유
  3. 쉬운게 아니네

0개의 댓글