A property wrapper type that can read and write a value managed by SwiftUI.
Int, Strings, Bool형을 포함하는 간단한 자료형에서 사용하도록 디자인되었습니다. 사용자가 직접 정의하고 앱 내에서 사용하는 class 또는 struct와 같은 더 복잡한 참조 유형을 위해 설계되지 않았습니다.
@State는 업데이트 될 때마다 뷰의 body 변수를 다시 계산하여 작동합니다. 따라서 뷰에 정수를 추적하는 State가 있고 정수에 1을 더하면 State가 이를 보고 뷰를 다시 렌더링합니다.
@State는 struct, class와 같은 복잡한 자료형도 추적할 수 있지만 추적하고 있는 객체의 멤버변수가 변해도 추적하고 있는 객체가 직접 변하지 않는이상 뷰를 랜더링 하지않는다.
class SomeObject: ObservableObject {
@Published var num: Int = 0
}
class EnviromentObject: ObservableObject {
@Published var string: String = "Hello grandChild"
}
struct GrandparentsView: View {
@StateObject var environmentObject = SomeObject()
var body: some View {
VStack {
ParentsView().environmentObject(environmentObject)
}
}
}
struct ParentsView: View {
@State var num = 0
@State var obejct = SomeObject()
@StateObject var stateObject = SomeObject()
var body: some View {
VStack {
Button(action: {
}, label: {
Text("num: \(num)")
})
Button(action: {
obejct.num+=1
}, label: {
Text("object.num: \(obejct.num)")
})
Button(action: {
stateObject.num+=1
}, label: {
Text("stateObject.num: \(stateObject.num)")
})
NavigationLink(
destination: ChildView(observedObject: stateObject),
label: {
Text("To Child")
})
}
}
}
struct ChildView: View {
@ObservedObject var observedObject: SomeObject
@EnvironmentObject var environmentObject: EnviromentObject
var body: some View {
VStack {
Button(action: {
observedObject.num+=1
}, label: {
Text("observedObject.num: \(observedObject.num)")
})
Text("GrandParents Tell: \(environmentObject.string)")
}
}
}
A property wrapper type that instantiates an observable object.
@StateObject는 복잡한 객체를 추적할 수 있다.
A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.
ObservedObject는 Observable Object를 한 뷰에서 다른 뷰로 전달하고자 할 때 사용됩니다.
상위뷰가 하위뷰에게 객체를 넘겨줄때 @ObservableObject를 사용한다 하지만 상위뷰가 하위하위하위뷰에 넘겨줄때와 같은경우 사용하면된다. @EnvironmentObject 값을 넘겨주면 모든 하위뷰가 상위뷰의 값을 이용할 수 있다.