gpt4 book ai didi

xcode - 使用变量时,SwiftUI Observable 未更新

转载 作者:行者123 更新时间:2023-12-04 10:55:11 25 4
gpt4 key购买 nike

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

不会工作:

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())

最佳答案

你的猜测是对的!!

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] ,它只是获取并创建新的 Person(此对象的地址与 self.mypeople.people[0] 对象不同),因此在这种情况下,您希望更改数组中的数据,您必须设置 self.mypeople.people[0] = people更改后 people.name
HERE有关引用类型和值类型的更多详细信息

关于xcode - 使用变量时,SwiftUI Observable 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59251238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com