Core data 如何在SwiftUI视图中更新核心数据信息
我陷入了僵局。我想显示CoreData中要编辑的数据,然后将其更新回数据库。似乎没有任何方法可以做到这一点,但这是一个基本的操作,我相信问题就在我这边 这是我的密码Core data 如何在SwiftUI视图中更新核心数据信息,core-data,view,swiftui,Core Data,View,Swiftui,我陷入了僵局。我想显示CoreData中要编辑的数据,然后将其更新回数据库。似乎没有任何方法可以做到这一点,但这是一个基本的操作,我相信问题就在我这边 这是我的密码 import SwiftUI import CoreData struct CustomerEditView: View { @Environment(\.managedObjectContext) var context @State var firstName = "" @
import SwiftUI
import CoreData
struct CustomerEditView: View
{
@Environment(\.managedObjectContext) var context
@State var firstName = ""
@State var lastName = ""
@State var phone = ""
@State var email = ""
@State var birthday = ""
var customer: Customer
var body: some View
{
//firstName = customer.firstName!
//lastName = customer.lastName!
//phone = customer.phone!
//email = customer.email!
return VStack
{
TextField("First Name", text: $firstName)
TextField("Last Name", text: $lastName)
TextField("Cell Phone", text: $phone)
TextField("EMail", text: $email)
TextField("Birthday", text: $birthday)
Button("Save")
{
do
{
//customer.birthday = self.birthday
customer.firstName = firstName
customer.lastName = lastName
customer.phone = phone
customer.email = email
try context.save()
}
catch
{
print(error.localizedDescription)
}
}
}
}
}
我尝试了许多方法来更新CoreData客户实体中的状态变量,但在SwiftUI中似乎没有任何方法可以在更新操作期间不触发有关修改状态值的警告。我会接受任何解决方案,但似乎应该有一种方法可以实现这一点,而无需使用临时状态变量,只需引用核心数据属性。这是一种方法
struct CustomerEditView: View
{
@Environment(\.managedObjectContext) var context
@State var firstName: String // << declare only
// ... other states are the same
var customer: Customer
init(customer: Customer) {
self.customer = customer
// create state with initial value from customer
_firstName = State(initialValue: customer.firstName ?? "") // << here !!
// ... other states are the same
}
var body: some View
{
// .. other your code
struct CustomerEditView:View
{
@环境(\.managedObjectContext)变量上下文
@State var firstName:String//我已经到处找了,但找不到下划线的定义位置。我在一段时间前看到它被引用了,但再也找不到它。@Russ,它是状态属性包装器的名称。它是由编译器自动生成的。感谢您提供这个答案,它对我来说也很有用。而且,它绝对是一个awfu更新数据的方法。不知道开发人员如何自己解决这个问题。