SwiftUI: The problem is saving data in CoreData

Viewed 35

I want to save the data in the database profileDB.lvl that is transferred from another property self.lvl

At the beginning of ContentView I prescribed:

@Environment(\.managedObjectContext) var managedObjectContext

And

@State public var lvl = 0
let profileDB = ProfileUser(context: self.managedObjectContext)

Then, in the button below, I prescribed the logic of saving:

Button(action: {
    withAnimation(.easeInOut){

        profileDB.lvl = Int16(self.lvl)

        do{
            if progress < 300{
                progress += 75
            } else if progress == 300{
                progress = 50
                self.lvl += 1
            }
            
            try self.managedObjectContext.save()
        } catch{
            print(error)
        }
    }
},
       label: {
    Text("Perform")
        .foregroundColor(Color.black)
        .font(.system(size: 18, design: .default))
})

And it turns out that the data is changed in self.lvl, but not assigned to profileDB.lvl
Am I having trouble with the correct implementation, what can help solve the problem?

1 Answers

What @jrturton is saying is twofold:

You are assigning the value of the @State var lvl to the managed object profileDB.lvl BEFORE you update @State var lvl. You are not binding @State var lvl to profileDB.lvl (nor would you want to) so it doesn't update when @State var lvl does. So, change the order:

Button(action: {
    withAnimation(.easeInOut){

        do{
            if progress < 300{
                progress += 75
            } else if progress == 300{
                progress = 50
                self.lvl += 1
            }
            profileDB.lvl = Int16(self.lvl)


            try self.managedObjectContext.save()
        } catch{
            print(error)
        }
    }
},
       label: {
    Text("Perform")
        .foregroundColor(Color.black)
        .font(.system(size: 18, design: .default))
})

However, you have another issue. Every time this view appears, you are creating a new managed object and giving it a value. That may be what you intend. Generally, you would pass in the one object that is keeping this particular user's profile, and would update that. Not create a new user with no other info except the updated level.

Related