BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

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?



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)
        .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 {
            } catch {
                print("Error saving record")


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: ?? initialDate)
//            _Id1 = State(initialValue: ?? initialId )
//        }
//        else
//        {
//            _titolo = State(initialValue: "")
//            _descrizione = State(initialValue:  "")
//            _data = State(initialValue: initialDate)
//            _Id1 = State(initialValue: initialId)
//        }
//    }

    var body: some View {

        NavigationView {


                Section {

                    TextField("Title", text: $titolo)

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

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

                Section {
                    Button("Salva") {

                        let nuovoDiarioEmotivo = Diario(context: moc)
               = UUID()
                        nuovoDiarioEmotivo.titolo = titolo
                        nuovoDiarioEmotivo.descrizione = descrizione



            .navigationTitle("Modifica il tuo Diario")



//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



remove the ? from diario.


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 ?


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


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


Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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

Reply to this topic…

You need to create an account or log in to reply.

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.