iOS: Delete ALL Core Data Swift

前端 未结 23 703
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 11:20

I am a little confused as to how to delete all core data in swift. I have created a button with an IBAction linked. On the click of the button I have the follow

23条回答
  •  隐瞒了意图╮
    2020-12-04 11:57

    Swift 4

    From iOS 9, there is the possibility of erasing persistent storage. For better maintenance – create NSPersistentStoreCoordinator extension with abstract function.

    extension NSPersistentStoreCoordinator {
        func destroyPersistentStore(type: String) -> NSPersistentStore? {
            guard 
                let store = persistentStores.first(where: { $0.type == type }),
                let storeURL = store.url 
            else {
                return nil
            }
    
            try? destroyPersistentStore(at: storeURL, ofType: store.type, options: nil)
    
            return store
        }
    }
    

    Then destroying SQLite persistent storage looks pretty simple:

    let coordinator = persistentContainer.persistentStoreCoordinator
    let store = coordinator.destroyPersistentStore(type: NSSQLiteStoreType)
    

    Recommendations

    1. Update destroyPersistentStore function which is no-nullable and throws specific errors, for example CoreDataError enum.
    2. Probably you want to refresh your persistent storage. For this, you can use addPersistentStore function of NSPersistentStoreCoordinator, with retrieved NSPersistentStore object from destroyPersistentStore.

提交回复
热议问题