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

SOLVED: Updating List view properly after object insertion/deletion in CoreData

Forums > SwiftUI

Hi all,

So I'm working on a simple task manager app so I can get the hang of using and learning Core Data, but for some reason adding or deleting a task isn't handled properly by the view. I'll let this gif do the talking:

The list shows duplicates of the same task, but when one of them is deleted it shows the task created before it. Here is my code for adding a task:

Button("Save Task") {
    if taskName != "" {
        let newTask = Task(context: moc)
        newTask.name = taskName
        newTask.date = taskDate
        newTask.tag = taskTag
        try? moc.save()
        dismiss()
    }
}

And here is the code for deletion:

List(taskArray) { task in
    HStack {
        Image(systemName: "square")
        .onTapGesture {
             moc.delete(task)
             try? moc.save()
        }
    }
}

Here is the full repo if y'all are interested: https://github.com/aabagdi/TaskMan

Thanks so much for any help!

2      

Hi! You need to remove id attribute in your TaskDataModel file. Core Data automatically makes your entities conform to Identifiable for you so you will never have to specify the id. As you added this attribute manually (and by default it is marked as optional), so when you add your new task, every single task is created with id set as nil. The result you can see on your screen.

3      

Ah ofc, that makes perfect sense, I totally overlooked that! Alternatively, I guess you can add the line newTask.id = UUID() to get it working properly. Thanks so much for the help!

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.