Aldo Lazuardi Aldo Lazuardi - 2 years ago 149
Swift Question

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

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)


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?

Answer Source

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)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download