Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill TextField with data from Core Data and update changes?

I am trying to learn how to Save, Edit and Delete data using Core Data. So far, with the help of this great community, I have managed to Save and Delete, but I don't know how to Edit and Update currently saved data.

Here is a simple example of an app I am working on. It is a list with items from Core Data. I am adding new list entries on a modal (AddItemView) and deleting them on EditItemView. I would like to edit and update data as well on the AddItemView view.

I managed to pass data to hint of TextField, but what I wanted is:

  1. pass the current data to text of TextField and make it editable
  2. Save/update the data after tapping

Core Data has 1 Entity: ToDoItem. It has 1 Attribute: title (String). Codegen: Class Definition, Module: Current Product Module.

I have added some additional comments in the code.

ContentView

import SwiftUI

struct ContentView: View {

    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(
        entity: ToDoItem.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \ToDoItem.title, ascending: true)
        ]
    ) var toDoItems: FetchedResults<ToDoItem>

    @State private var show_modal: Bool = false

    var body: some View {
        NavigationView {
            List{
                ForEach(toDoItems, id: \.self) {todoItem in

                    NavigationLink(destination: EditItemView(todoItem: todoItem)) {

                        Text(todoItem.title ?? "")
                        .font(.headline)
                    }
                }

            }
            .navigationBarTitle(Text("My List"))
            .navigationBarItems(trailing:
                Button(action: {
                    self.show_modal = true
                }) {
                    Text("Add")
                }.sheet(isPresented: self.$show_modal) {
                    AddItemView().environment(\.managedObjectContext, self.managedObjectContext)
                }
            )
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        return ContentView().environment(\.managedObjectContext, context)
    }
}

AddItemView

import SwiftUI

struct AddItemView: View {

    @Environment(\.presentationMode) var presentationMode
    @Environment(\.managedObjectContext) var managedObjectContext

    @State private var title = ""

    var body: some View {
        NavigationView {
            ScrollView {

                TextField("to do item...", text: $title)
                    .font(Font.system(size: 30))

                Spacer()

            }
            .padding()
            .navigationBarTitle(Text("Add Item"))

            .navigationBarItems(
                leading:
                Button(action: {
                    self.presentationMode.wrappedValue.dismiss()
                }) {
                    Text("Cancel")
                },

                trailing:
                Button(action: {
                    let toDoItem = ToDoItem(context: self.managedObjectContext)
                    toDoItem.title = self.title

                    do {
                        try self.managedObjectContext.save()
                    }catch{
                        print(error)
                    }

                    self.presentationMode.wrappedValue.dismiss()
                }) {
                    Text("Done")
                }
            )

        }
    }
}

struct AddItemView_Previews: PreviewProvider {
    static var previews: some View {
        AddItemView()
    }
}

EditItemView

import SwiftUI

struct EditItemView: View {

    @Environment(\.managedObjectContext) var managedObjectContext
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    var todoItem: ToDoItem

    //I am only using this newTitle variable, because I don't know how to properly bind TextField to todoItem.title
    @State private var newTitle = ""

    var body: some View {
        ScrollView {

            TextField(todoItem.title != nil ? "\(todoItem.title!)" : "", text: $newTitle)

            //TextField("to do...", text: (todoItem.title != nil ? "\(todoItem.title!)" : ""))
            //ERROR
            //I need something like the above, but this gives me an error: Cannot convert value of type 'String' to expected argument type 'Binding<String>'

        }
        .padding()
        .navigationBarTitle(Text("Edit item"))
        .navigationBarItems(
            trailing:
            Button(action: {
                print("Delete")

                self.managedObjectContext.delete(self.todoItem)
                do {
                    try self.managedObjectContext.save()
                    self.presentationMode.wrappedValue.dismiss()
                }catch{
                    print(error)
                }

            }) {
                Text("Delete")
                    .foregroundColor(.red)
            }
        )
    }
}

struct EditItemView_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        //Test data
        let todoItem = ToDoItem.init(context: context)
        todoItem.title = "Title"
        return EditItemView(todoItem: todoItem).environment(\.managedObjectContext, context)
    }
}
like image 928
mallow Avatar asked Dec 08 '19 04:12

mallow


1 Answers

I would do it in the following way

TextField("_here_is_label_name_", text: $newTitle, onCommit: {
    self.todoItem.title = self.newTitle
    try? self.managedObjectContext.save()
})
.onAppear {
    self.newTitle = self.todoItem.title != nil ? "\(self.todoItem.title!)" : ""
}
.onDisappear {
    self.todoItem.title = self.newTitle
    try? self.managedObjectContext.save()
}

Update: added .onDisappear modifier; duplicated code can be extracted in dedicated private function to have good design.

like image 184
Asperi Avatar answered Sep 22 '22 22:09

Asperi