问题
I tried to migrate coreData to new version, I'm following this step:
Add a new Model Version (Select name.xcdatamodeld then Editor->Add model Version) before making any changes, if you have an app already submitted to App Store which is using the earlier model version.
Then, Add a new file from Core Data Tab, as Mapping Model Select, Source Model (Model Version which the submitted App is using) Destination Model (Model Version in which you have done the Changes)
source
But my data mostly are images and app crash because it takes a lot of memory. So I want to delete old data model and its datas and create empty new model data when user update their app. How to do this?
回答1:
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.
来源:https://stackoverflow.com/questions/36714388/how-to-simply-delete-old-core-data-and-rebuilt-the-new-one