由于某种原因,当将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())
答案 0 :(得分:2)
您的猜测是正确的!
人对象是引用类型,人对象是值类型。
在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]
行获得人员时,它只是获得并创建一个新的Person(此对象的地址与self.mypeople.people [0]对象有所不同),因此在这种情况下,您期望更改数组中的数据,更改self.mypeople.people[0] = people
后必须设置people.name
HERE有关引用类型和值类型的更多详细信息