6

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?

Community
  • 1
  • 1
Aldo Lazuardi
  • 1,898
  • 2
  • 19
  • 34

1 Answers1

3

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.

A. L. Strine
  • 611
  • 1
  • 7
  • 23
Binarian
  • 12,296
  • 8
  • 53
  • 84
  • does it will rebuilt the core data every time user open the app? – Aldo Lazuardi Apr 19 '16 at 10:16
  • 1
    @AldoLazuardi It is up to you when you want a fresh database. One option would be to create a text file in which you save the version of your Database. If the version is too old and has to be rebuilt you delete the store file and recreate an empty one. – Binarian Apr 19 '16 at 10:23
  • Delete -shm and -wal files as well with the related Store file – Ammar Mujeeb Jun 17 '16 at 06:04