๐Ÿ…ฟ๏ธObservableObject

SwiftUI โŸฉ Data Flow โŸฉ ObservableObject

When a class conforms to the ObservableObject protocol, any changes to its published values will cause all views using those values to automatically update, reflecting the changes.

// โญ๏ธ 1. declare an observable object type
final class ModelData: ObservableObject {   
 
    // โญ๏ธ 2. declare published properties
    @Published var landmarks: [Landmark] = load("landmarkData.json")               
}

// app
struct LandmarksApp: App {
    
    // โญ๏ธ 3. initialize an observable object (data model)
    @StateObject private var modelData = ModelData() 
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                // โญ๏ธ 4. put the model object in the environment.
                // ------------------------------------------------
                //       any subview can access this model object 
                //       through `@EnvironmentObject` automatically. (see 6.)
                .environmentObject(modelData)         
        }
    }
}

// any subview in the view hierarchy
struct LandmarkList: View {

    // โญ๏ธ 5. adopt the model object as an `@EnvironmentObject`
    // --------------------------------------------------------
    // `modelData` property gets its value AUTOMATICALLY, as long as
    // `environmentObject(_:)` modifier has been applied to a parent view.
    @EnvironmentObject var modelData: ModelData      
    
    var body: some View { ... }
}
  • An observable object is a custom object (reference type) for your data that can be bound to a view from storage in SwiftUIโ€™s environment.

ๅ•้กŒ

ๅœจ่ทŸ CS193P ๅˆฐ็ฌฌไธ‰่ชฒ็š„ๆ™‚ๅ€™๏ผŒๅฆ‚ๆžœๆŒ‰็…ง่ชฒ็จ‹ไธŠ็š„็จ‹ๅผ็ขผๅŽŸๅฐไธๅ‹•็š„็…งๆŠ„๏ผŒ็จ‹ๅผๅฏไปฅๆญฃๅธธๅŸท่กŒใ€‚

ไฝ†ๅฆ‚ๆžœๆ“…่‡ชๅฐ‡ Card ้€™ๅ€‹ struct ๆ”นๆˆไธๅƒ…้ตๅพช Identifiable ๅŒๆ™‚ไนŸ้ตๅพช Equatable๏ผŒ้€™ๆ™‚ๅฐฑๅ‡บ็พๅ•้กŒไบ†๏ผšใ€ŒๅœจๆŒ‰ๅก็‰‡็š„ๆ™‚ๅ€™๏ผŒๅก็‰‡ไธๆœƒ็ฟป้ขใ€๏ผŒ้€™ๅ•้กŒไผผไนŽ่ทŸ ForEach(data){ ... } ่ชžๆณ•่ฃก้ข๏ผŒdata ้ƒจๅˆ†็š„ .id ๆœ‰้—œไฟ‚ใ€‚

ๅฐฑ็ฎ— @Published var viewModel ๆ›ดๆ–ฐไบ†๏ผŒไฝ†ๅœจ ForEach(viewModel.cards) ่ฃก้ข็š„ cards ็š„ id ไธฆๆฒ’ๆœ‰่ฎŠๆ›ด๏ผŒๅ†ๅŠ ไธŠ Card ๆœฌ่บซ้ตๅพช Equatable (้€™้ปžๅพˆ้‡่ฆ๏ผŒๅ› ็‚บๅฆ‚ๆžœๆฒ’ๆœ‰ Equatable๏ผŒ็จ‹ๅผๅฏๆญฃๅธธๅŸท่กŒ)๏ผŒ้€ ๆˆ SwiftUI ๅˆคๆ–ท EmojiMemoryGameView ็š„ body ่ฃก้ข็š„ ForEach ้ƒจๅˆ†ไธ้œ€ๆ›ดๆ–ฐ๏ผŒๅ› ๆญคๅฐฑไธๆœƒ็ฟป้ขไบ†ใ€‚

ๆœ‰ Equatable ่ทŸๆฒ’ๆœ‰ Equatable ๆ€Ž้บผๅทฎ้‚ฃ้บผๅคšๅ‘ข๏ผŸSwiftUI ๆ˜ฏๅฆ‚ไฝ•ๅˆคๆ–ทไธ€ๅ€‹ view ๅˆฐๅบ•่ฆไธ่ฆๆ›ดๆ–ฐๅ‘ข๏ผŸ

ๅƒ่€ƒ่ณ‡ๆ–™

Last updated