How to simply delete old core data and rebuilt the new one?

家住魔仙堡 提交于 2019-12-04 10:11:08
Binarian

If the data model changes you can simply check what model the database file has. If it is not the new one, delete the file specified in the StoreCoordinator with NSFileManager and init your StoreCoordinater and NSManagedContext again to create a new one.

Something like that (not tested code):

var error: NSError
var applicationDocumentsDirectory: NSURL = NSFileManager.defaultManager().URLsForDirectory(NSDocumentDirectory, inDomains:NSUserDomainMask).lastObject
let storeURL: NSURL = applicationDocumentsDirectory.URLByAppendingPathComponent("Database.sqlite")
NSFileManager.defaultManager().removeItemAtPath(storeURL.path, error)

Update for Swift 4:

    do
    {
        var applicationDocumentsDirectory: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
        let storeURL: URL = applicationDocumentsDirectory.appendingPathComponent("Database.sqlite")
        try FileManager.default.removeItem(atPath: storeURL.path)
    }
    catch
    {
        print(error.localizedDescription)
    }

If the model did not change, you need to save the information of the update anywhere. A text file, in the database itself or in UserDefaults. You just need a flag to check, whether the database has been updated/cleaned.

You can then also delete the database like above or fetch all objects and delete them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!