Why an ObservedObject array is not updated in my SwiftUI application?

前端 未结 4 1466
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 00:53

I\'m playing with SwitUI, trying to understand how ObservableObject works. I have an array of Person objects. When I add a new Person into the array, it is reloaded in my Vi

4条回答
  •  星月不相逢
    2020-11-30 01:29

    Person is a class, so it is a reference type. When it changes, the People array remains unchanged and so nothing is emitted by the subject. However, you can manually call it, to let it know:

    Button(action: {
        self.mypeople.objectWillChange.send()
        self.mypeople.people[0].name="Jaime"    
    }) {
        Text("Add/Change name")
    }
    

    Alternatively (and preferably), you can use a struct instead of a class. And you do not need to conform to ObservableObject, nor call .send() manually:

    import Foundation
    import SwiftUI
    import Combine
    
    struct Person: Identifiable{
        var id: Int
        var name: String
    
        init(id: Int, name: String){
            self.id = id
            self.name = name
        }
    
    }
    
    class People: ObservableObject{
        @Published var people: [Person]
    
        init(){
            self.people = [
                Person(id: 1, name:"Javier"),
                Person(id: 2, name:"Juan"),
                Person(id: 3, name:"Pedro"),
                Person(id: 4, name:"Luis")]
        }
    
    }
    
    struct ContentView: View {
        @ObservedObject var mypeople: People = People()
    
        var body: some View {
            VStack{
                ForEach(mypeople.people){ person in
                    Text("\(person.name)")
                }
                Button(action: {
                    self.mypeople.people[0].name="Jaime"
                }) {
                    Text("Add/Change name")
                }
            }
        }
    }
    

提交回复
热议问题