Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftData how to delete data from an entity

Tags:

swiftdata

I am working on migrating my code into SwiftData and can't seem to find any good answers on how to delete the data in that entity. In Swift I had this function created:

class func deleteEntity(entity: String) {
  let fetchRequest1: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: entity)//entity.fetchRequest()
  let batchDeleteRequest1 = NSBatchDeleteRequest(fetchRequest: fetchRequest1)
  _ = try?  PersistanceController.shared.container.viewContext.execute(batchDeleteRequest1)
  print("Deleting coredata entity: \(entity)")
}

in Xcode 15 (beta) I have my context:

container = try ModelContainer(for: [SectionsSD.self, ArticleSD.self])
let context = ModelContext(container)

I want to delete the content that's in ArticlesSD.self I've been told to look at using: ModelContext.delete(_:) or ModelContext.delete(model:where:includesubentities:), but I can't figure out the right syntax on how to use these

Any help would be appreciated. An example or sample code would be helpful.

like image 806
David Avatar asked Oct 31 '25 13:10

David


2 Answers

The signature of the context.delete changed to

delete(model: T.Type, where predicate: Predicate? = nil, includeSubclasses: Bool = true)

Therefore, the code of Tom Harrington has to be adapted a bit to accommodate these changes. What he says still holds true, the idea is the same. The following extension allows to conveniently delete all entries of a Type

extension ModelContext {
    func deleteAll<T>(model: T.Type) where T : PersistentModel {
        do {
            let p = #Predicate<T> { _ in true }
            try self.delete(model: T.self, where: p, includeSubclasses: false)
            print("All of \(model.self) cleared !")
        } catch {
            print("error: \(error)")
        }
    }
}

It can be called like

modelContext.deleteAll(model: ArticlesSD.self)
like image 175
Deitsch Avatar answered Nov 02 '25 12:11

Deitsch


I haven't been able to verify this for sure but it looks like what you want is

context.delete(model: ArticlesSD.self)

There are other arguments for this function but one is optional and one has a default value. If you want to be clear about them, you could write it as

context.delete(model: ArticlesSD.self, where: NSPredicate(value: true), includeSubentities: false)

The predicate tells the context which items to delete, and a "true" predicate means to delete all of them. The subentries argument doesn't matter unless you've created sub-entities (and you would know if you did).

like image 35
Tom Harrington Avatar answered Nov 02 '25 13:11

Tom Harrington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!