【问题标题】:SwiftUI Observable not being updated when using a variableSwiftUI Observable 使用变量时未更新
【发布时间】:2020-04-02 16:42:02
【问题描述】:

由于某种原因,当将 Observable 的对象分配给变量然后更改它时 - 视图不会更新。 但如果我直接通过它的索引访问它 - 它会:

不起作用:

var people = self.mypeople.people[0]
people.name = 'test'

有效:

self.mypeople.people[0].name = 'test'

我的猜测是关于引用,但我不确定:(

示例代码:

//: A UIKit based Playground for presenting user interface

import SwiftUI
import PlaygroundSupport
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: {
                var people = self.mypeople.people[0]
                // this howver works:
                // self.mypeople.people[0].name = 'Test'
                people.name="Jaime2"
            }) {
                Text("Change name")
            }
        }
    }
}


PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())

【问题讨论】:

    标签: xcode swiftui observableobject


    【解决方案1】:

    你猜对了!!

    People对象是引用类型,Person对象是值类型。

    来自here 我可以通过这段代码检查对象的类型:

    func isReferenceType(toTest: Any) -> Bool {
        return type(of: toTest) is AnyObject
    }
    
    isReferenceType(toTest: Person(id: 1, name:"Javier")) //false
    isReferenceType(toTest: People()) //true
    

    所以当你通过这一行var people = self.mypeople.people[0] 获取人时,它只是获取并创建新的人(这个对象的地址与 self.mypeople.people[0] 对象不同),所以在这种情况下你希望改变你的数组中的数据,更改people.name后必须设置self.mypeople.people[0] = people

    HERE 了解更多关于引用类型和值类型的详细信息

    【讨论】:

    • 非常感谢!搜索时找不到此信息。
    猜你喜欢
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多