๐Ÿ…ฟ๏ธObservableObject

SwiftUI โŸฉ Data Flow โŸฉ ObservableObject

  • 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.

  • SwiftUI watches for any changes to observable objects that could affect a view, and displays the correct version of the view after a change.

// โญ๏ธ 1. import `Combine` framework
import Combine                      // for `ObservableObject`

// โญ๏ธ 2. conforms to `ObservableObject`
final class ModelData: ObservableObject {
    // โญ๏ธ 3. publish properties
    /// An observable object needs to publish any changes to its data,
    /// so that its subscribers can pick up the change.
    @Published var landmarks: [Landmark] = load("landmarkData.json")
}

struct LandmarksApp: App {
    
    // โญ๏ธ 4. use `@StateObject` to initialize a model object
    @StateObject private var modelData = ModelData()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                // โญ๏ธ 5. put the model object in the environment
                .environmentObject(modelData)
        }
    }
}

struct LandmarkList: View {
    
    // โญ๏ธ 6. adopt the observable object
    /// `modelData` property gets its value AUTOMATICALLY, as long as
    /// `environmentObject(_:)` modifier has been applied to a *parent*.
    @EnvironmentObject var modelData: ModelData
    
    var body: some View { ... }
}

ๅ•้กŒ

ๅœจ่ทŸ 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