TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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.