Delete/Reset all entries in Core Data?

后端 未结 30 3190
天命终不由人
天命终不由人 2020-11-22 16:00

Do you know of any way to delete all of the entries stored in Core Data? My schema should stay the same; I just want to reset it to blank.


Edit

30条回答
  •  日久生厌
    2020-11-22 16:15

    Assuming you are using MagicalRecord and have a default persistence store:

    I don't like all the solutions that assume certain files to exist and/or demand entering the entities names or classes. This is a Swift(2), safe way to delete all the data from all the entities. After deleting it will recreate a fresh stack too (I am actually not sure as to how neccessery this part is).

    It's godo for "logout" style situations when you want to delete everything but have a working store and moc to get new data in (once the user logs in...)

    extension NSManagedObject {
    
        class func dropAllData() {
    
            MagicalRecord.saveWithBlock({ context in
    
                for name in NSManagedObjectModel.MR_defaultManagedObjectModel().entitiesByName.keys {
                    do { try self.deleteAll(name, context: context) }
                    catch { print("⚠️ ✏️ Error when deleting \(name): \(error)") }
                }
    
                }) { done, err in
                    MagicalRecord.cleanUp()
                    MagicalRecord.setupCoreDataStackWithStoreNamed("myStoreName")
            }
        }
    
        private class func deleteAll(name: String, context ctx: NSManagedObjectContext) throws {
            let all = NSFetchRequest(entityName: name)
            all.includesPropertyValues = false
    
            let allObjs = try ctx.executeFetchRequest(all)
            for obj in allObjs {
                obj.MR_deleteEntityInContext(ctx)
            }
    
        }
    }
    

提交回复
热议问题