๐๐ป ์ค์ํํธ์์ ObservedObject์ StateObject๋ฅผ ์ฌ์ฉํ๋ ๊ฐ๋จํ ๋ฐฉ๋ฒ์
๋๋ค.
This is a simple way to use ObservedObject and StateObject in Swift.
โ๏ธ @StateObject์ย @ObservedObject๋ ๋๋ค ๋ทฐ์ ๋ฐ์ธ๋ฉํ๋ ๋ฐฉ๋ฒ์ด์ง๋ง, ๋์ ์ฝ๊ฐ์ ์ฐจ์ด๊ฐ ์์ต๋๋ค.
Both @StateObject and @ObservedObject are methods for binding to a view, but there are slight differences between the two.
โ๏ธ @StateObject
— ์ผ๋ฐ์ ์ผ๋ก ๋ทฐ์์ ์ง์ ์ํ ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ณ ๊ด๋ฆฌํ ๋ ์ฌ์ฉํฉ๋๋ค.
It is generally used when creating and managing state objects directly in the view.
— ๋ทฐ๊ฐ ์ฒ์ ์์ฑ๋ ๋๋ง ํด๋น ObservableObject ์ธ์คํด์ค๋ฅผ ์ด๊ธฐํํ๊ณ , ๋ทฐ๊ฐ ๋ค์ ๋ ๋๋ง๋๊ฑฐ๋ ๊ฐฑ์ ๋ ๋๋ ๊ธฐ์กด ์ธ์คํด์ค๋ฅผ ์ ์งํฉ๋๋ค.
Initialize the ObservableObject instance only when the view is first created, and maintain the existing instance when the view is re-rendered or updated.
— ๋ทฐ์์ ์ง์ ์ํ ๊ด๋ฆฌ๋ฅผ ํ ๋ ์ฌ์ฉํฉ๋๋ค.
It is used when managing state directly in the view.
— ์๋์ ์ฝ๋๊ฐ ์ด ๋ถ๋ถ์ ํด๋นํฉ๋๋ค.
The code below corresponds to this part.
โ๏ธ @ObservedObject
— ์ธ๋ถ์์ ์ด๋ฏธ ์์ฑ๋ ObservableObject๋ฅผ ์ ๋ฌ๋ฐ์ ์ฌ์ฉํฉ๋๋ค.
It receives and uses an ObservableObject that has already been created externally.
— ๋ทฐ๊ฐ ๋ค์ ์์ฑ๋ ๋๋ง๋ค ObservableObject ์ธ์คํด์ค๊ฐ ๊ณ์ ์๋ก ์์ฑ๋๋ ๊ฒฝ์ฐ๊ฐ ์์ ์ ์์ต๋๋ค.
There may be cases where new ObservableObject instances are created every time the view is recreated.
— ๊ทธ๋์ ๋ถ๋ชจ๋ทฐ๋ฅผ ์์๋ทฐ์ ์ ๋ฌํ ๋ ์ฌ์ฉํฉ๋๋ค.
So, it is used when passing a parent view to a child view.
๐๐ป ์ฝ๋ / Code
import SwiftUI
import Combine
class UserSettings: ObservableObject {
@Published var username = "Anonymous"
}
struct ContentView: View {
// @StateObject๋ SwiftUI์ state storage(๋ทฐ์ ๋ผ์ดํ ์ธ์ดํด ๋์ ๋ณด๊ด๋๋ ์ ์ฅ์)์
// ์ธ์คํด์ค๋ฅผ ์ ์ฅํ๊ณ , ์ฒ์ ๋ทฐ๊ฐ ์์ฑ๋ ๋๋ง ์ด๊ธฐํํ๋๋ก ๋ณด์ฅํฉ๋๋ค.
// @StateObject stores an instance in SwiftUI's state storage (which is kept throughout the view's lifecycle) and ensures that it is initialized only when the view is first created.
@StateObject var settings = UserSettings()
// @ObservedObject๋ ๊ตฌ์กฐ์ฒด์ ์ด๊ธฐํ ์์ ์ ๊ณ์ํด์UserSettings()๋ฅผ ๋ค์ ์คํ ํฉ๋๋ค.
// @ObservedObject will continually re-run UserSettings() at the time of initialization of the struct.
//@ObservedObject var settings = UserSettings()
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("User name:\(settings.username)")
.padding()
Button("John Doe"){
settings.username = "Jhon Doe"
}
Button("Anonymous"){
settings.username = "Anonymous"
}
Text("Child View")
}
.padding()
}
}
#Preview {
ContentView()
}
โ๏ธ ์คํฌ๋ฆฐ ์ท / ScreenShot
