GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

How to modify data in corredata from a view

Forums > SwiftUI

How to modify data in corredata from a view, some one can help me understaning the logic?

I have recreate a view with the form and i would like to put the data in the form automatcly, so people could change it and i would like to save again.

But I ahve problem to pass the data in the form fild

For example I create

@State var titolo = ""

TextField("Task Name", text: $titolo)

How can I pass to the text field the record?

Thanks

2      

In order to provide you with proper logic it's advisable that you provide more information about the structure of the workflow in your views. If you want to use core data entity you probably sent fetch request to core data, and you recevied fetch request results, and somehow placed it on your view, then probalby you tap an item and at this particular moment you can pass item to view where you can display that info in the TextField and modify it. You cannot throw a bunch of items in your TextField, without choosing an item you want to work with. Then when you have single item to work with you can modify and save edited item in moc or managed object context. But this is only my guesses :) For sure there are many other ways to do that, but without knowing how you structured your workflow it is rather difficult to say.

Possible code might look something like this

struct ModifyView: View {
    @Environment(\.managedObjectContext) var moc
    @Environment(\.dismiss) var dismiss

    @State private var inputTitle = ""

    // This item is passed from the view where you fetched data from CoreData
    let book: Books?

    var body: some View {
        VStack {
            TextField("Insert Title", text: $inputTitle)
                .textFieldStyle(.roundedBorder)
        }
        .navigationTitle("Modify Book")
        .toolbar {
            ToolbarItem {
                Button("Save") {
                    let newTitle = inputTitle.trimmingCharacters(in: .whitespaces)
                    if !newTitle.isEmpty {
                        Task(priority: .high) {
                            await saveBook(title: newTitle)
                        }
                    }
                }
            }
        }
        .onAppear {
          inputTitle = book?.title ?? ""
        }
    }

    func saveBook(title: String) async {
        await moc.perform {
            book?.title = title

            do {
                try moc.save()
                dismiss()
            } catch {
                print("Error saving record")
            }
        }
    }
}

2      

import SwiftUI

struct ModifyDiarioView: View {

    //let diario: Diario

    // questa forse è la soluzione

    @ObservedObject var diario: Diario

    @Environment(\.managedObjectContext) var moc
    @Environment(\.dismiss) var dismiss

//    @State var selectedTaskItem: Diario?

    @State  var titolo = ""
    @State  var descrizione = ""
//    @State  var data: Date
//    @State  var Id1: UUID

//    init(passedTaskItem: Diario?, initialDate: Date, initialId: UUID)
//    {
//        if let diario = passedTaskItem
//        {
//            _selectedTaskItem = State(initialValue: diario)
//            _titolo = State(initialValue: diario.titolo ?? "")
//            _descrizione = State(initialValue: diario.descrizione ?? "")
//            _data = State(initialValue: diario.data ?? initialDate)
//            _Id1 = State(initialValue: diario.id ?? initialId )
//
//
//        }
//        else
//        {
//            _titolo = State(initialValue: "")
//            _descrizione = State(initialValue:  "")
//            _data = State(initialValue: initialDate)
//            _Id1 = State(initialValue: initialId)
//
//        }
//    }

    var body: some View {

        NavigationView {

            Form{

                Section {

                    TextField("Title", text: $titolo)

                    //TextField("Comincia da qui a scrivere seguendo le indicazione ABC", text: $descrizione)
                        .padding(.all)
                    TextEditor(text: $descrizione).lineSpacing(10)

                }
                .padding(.horizontal, 16)
                .onAppear {
                          titolo = diario?.titolo ?? ""
                        }

                Section {
                    Button("Salva") {

                        let nuovoDiarioEmotivo = Diario(context: moc)
                        nuovoDiarioEmotivo.id = UUID()
                        nuovoDiarioEmotivo.titolo = titolo
                        nuovoDiarioEmotivo.descrizione = descrizione
                        nuovoDiarioEmotivo.data = Date.now

                        try? moc.save()
                        dismiss()

                    }
                }

            }
            .navigationTitle("Modifica il tuo Diario")
            .navigationBarTitleDisplayMode(.inline)

        }

    }
}

//struct ModifyDiarioView_Previews: PreviewProvider {
//    static var previews: some View {
//        ModifyDiarioView()
//    }
//}

I try to insert ho add .onAppear { titolo = diario?.titolo ?? "" }

                    but i have thi error

/Users/davide/Documents/swiftui100day/Diario-emotivo/Diario-emotivo/ModifyDiarioView.swift:83:42: error build: Cannot use optional chaining on non-optional value of type 'Diario'

Thanks for your help

2      

@Bnerd  

remove the ? from diario.

3      

As @Bnerd correclty indicated, you have to remove ? aka optional chaining. In my example i passed the item which is optional let book: Books?. In your code you are using @ObservedObject var diario: Diario which is non-optional. So there is no need for ?

3      

Thank you very much for the help you have given me, I am truly grateful. You saved me a lot of time. As much as I try to follow the tutorials this part is still quite difficult for me.

Good evening

2      

Always welcome! We all gone through this, it takes some time to absorb CoreData mistery. Still a lot to learn even for myself :)

4      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Transform your career with the iOS Lead Essentials. This Black Friday, unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a free crash course.

Save your spot

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.