Jimbo17
Jimbo17

Reputation: 13

Unable to delete SwiftData object

I am working on migrating my app to SwiftData and testing out some things. I have a custom made toolbar that shows among other things the various objects in a @Model. When I drag one of these to the trash it deletes the object, but the screen never updates and the object is never actually deleted even after calling save.

I've tried the normal way:

modelContext.delete(object)
try! modelContext.save()

I also added a delete function to the Model itself to attempt that way and it also fails to remove itself from the screen:

    func delete(context: ModelContext) {
        print("DELETING object through Delete function..")
        context.delete(self)
        try! context.save()
    }

I'm only using a simple query to read these in various views, is it not deleting because other views currently have the object in use? There are a handful of views that are querying like this:

@Query var myObjects: [Object]

I am not trying to delete all items just one specific object within the Array. The other example found searching here shows the entire SwiftData Array being deleted, which is not what I’m trying to do. That answer suggests deleting one at a time, which is what I’m doing and that is not working. I have also tried another @Model and it experiences the exact same behavior. I have run save() in the modelContext as well as waited a while, restarted the app, the values are not being removed from SwiftData.

=======

Update: After testing in a basic scenario I realize what I was doing wrong. I was listing my objects like this:

ForEach(object) { object in
    Text("My Object etc.")
        .draggable(object) {
            Text("My Object Preview")
        }
}

Later I had a dropDestination where I was trying to delete, but I was attempting to delete the object that was dropped which is the read-only version.

Incorrect Drop Destination code:

    Text("Drop Zone")
        .dropDestination(for: Object.self) { droppedObjects, location in 
            droppedObjects.forEach { object in
                modelContext.delete(object)
                try! modelContext.save()
            }
            return true
         }

This correct way to do this is to find the index of the object in the Array and delete that:

    Text("Drop Zone")
        .dropDestination(for: Object.self) { droppedObjects, location in 
            droppedObjects.forEach { object in
                if let index = myObjects.firstIndex(where: {$0.id == object.id}) {
                    modelContext.delete(myObjects[index])
                    try! modelContext.save()
                }
            }
            return true
         }

Upvotes: 0

Views: 35

Answers (0)

Related Questions