我能够在 CoreData 中保存对象。我的实体属性是字符串类型,并将输入的内容保存到文本字段中。我可以使用我指定的任何索引的 FetchedEntityRequest[index] 更新属性,但我无法保存传递到 DeatailView 的选定属性。请参阅下面的示例代码。
//save Attribute
func saveButtonTapped(text: String?) {
if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
let Entity.attribute: String = Entity(context: context)
Entity.attribute: = text
if context.hasChanges {
do {
try context.save()
} catch {
print(error.localizedDescription)
}
}
// pass attribute to DetailView from List View
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(
entity: Entity.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \Entity.attribute, ascending: true)
]
) var fetchedEntityRequest: FetchedResults<Entity>
var body: some View {
NavigationView {
List {
ForEach(fetchedEntityRequest, id: \.self) { entity in
VStack {
HStack {
Text(entity.attribute ?? "")
.font(.headline)
Spacer()
NavigationLink(destination: EditLyricsView(text: entity.attribute ?? "")) {
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
//DetailView - updating the index specified and saving changes to coredata.
@State var text: String = ""
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(
entity: Entity.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \Entity.attribute, ascending: true)
]
) var fetchedEntityRequest: FetchedResults<Entity>
var body: some View {
NavigationView {
VStack {
TextView(text: $text)
} .navigationBarTitle(Text("self.text"), displayMode: .inline)
.navigationBarItems(leading: Button("Home") {
presentationMode.wrappedValue.dismiss()
}, trailing: Button("Save") {
fetchedEntityRequest.forEach { i in
var index: Int = 0
fetchedEntityRequest[index].setValue(text, forKey: "Entity.attribute")
presentationMode.wrappedValue.dismiss()
}
}
}