UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Update data using Core Data

Forums > SwiftUI

Here https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-a-core-data-fetch-request-using-fetchrequest Paul goes over how to create, read and delete data, but how do you update it??

Here is the example he uses and I added a button for the update:

import SwiftUI

struct ContentView: View {

    @FetchRequest(
        entity: ProgrammingLanguage.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \ProgrammingLanguage.name, ascending: true),
            NSSortDescriptor(keyPath: \ProgrammingLanguage.creator, ascending: false)
        ]
    ) var languages: FetchedResults<ProgrammingLanguage>

    var body: some View {

        VStack {

            List(languages, id: \.self) { language in
                Text(language.name ?? "Unknown")
            }

            Button(action: {

            }) {
                Text("Update")
            }

            Spacer()
        }

    }
}

Thank you

3      

Never mind, I figure it out, it's just getting language.name inside the loop and seting it to a new value :) Maybe an ex: language.name = "new value"

3      

you qcan do a custom detail view as well

before the view body:

@ObservedObject var teammates: Teammate
@State public var email: String
@State public var id: UUID
@State public var lastName: String
@State public var firstName: String

var scoreView = ScoreViewModel()

init(teammate: Teammate) {
    self.teammates = teammate
    self._email = State(initialValue: teammate.email ?? "Unknown email")
    self._id = State(initialValue: teammate.id ?? UUID())
    self._lastName = State(initialValue: teammate.wrappedLastName)
    self._firstName = State(initialValue: teammate.wrappedFirstName)

}

// in the view body: a button or tapGesture...

let teammate = self.teammates
                    teammate.id = self.id
                    teammate.email = self.email
                    teammate.createdAt = Date()
                    teammate.lastName = self.lastName
                    teammate.firstName = self.firstName

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.