CoreData Lightweight migration issue

Viewed 649

I have written this app in Swift 5 and is already LIVE in App Store.

Now, I just want to add a new single boolean attribute to one existing entity in coredata.

For this purpose, I followed steps:

  1. Added version to Project.xcdatamodeld (It auto created Project 2.xcdatamodel file inside it)
  2. Set this version as default
  3. Add one attribute to entity in this new version file.
  4. Added properties shouldMigrateStoreAutomatically and shouldInferMappingModelAutomatically to NSPersistentContainer in AppDelegate class.

Issue:

While in app, I am successfully able to save data in coredata and retrieve from coredata in any ViewController but, if app opens from start, it cannot find previous file and recreates coredata file.

Whenever I open app, it shows error in xCode console:

Connecting to sqlite database file at "/dev/null"

AppDelegate code:

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {

let container = NSPersistentContainer(name: "Project")

let description = NSPersistentStoreDescription()
description.shouldMigrateStoreAutomatically = true
description.shouldInferMappingModelAutomatically = true
container.persistentStoreDescriptions=[description]

container.loadPersistentStores(completionHandler: { (storeDescription, error) in
    if let error = error as NSError? {
        
        fatalError("Unresolved error \(error), \(error.userInfo)")
    }
})
return container }()

Tutorial I followed: Medium

2 Answers

You need to specify the URL for the location of the actual model's database location.

 guard let storeURL = try? FileManager
   .default
   .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
   .appendingPathComponent("yourModel.sqlite") else {
      fatalError("Error finding Model from File Manager")
    }
    
    let container = NSPersistentContainer(name: yourModelName, managedObjectModel: yourModelInstance)
    
    let description = NSPersistentStoreDescription(url: storeURL)
    description.type = NSSQLiteStoreType
    description.shouldMigrateStoreAutomatically = true
    description.shouldInferMappingModelAutomatically = true
    container.persistentStoreDescriptions = [description]
    
    container.loadPersistentStores(completionHandler: { storeDescription, error in

The error message could indicate that the app doesn't know where to find or save the database files. The phrase "/dev/null" indicates in memory storage.

Try to use

let description = NSPersistentStoreDescription(url: <- File url to the main database file ->)

instead of the the current instantiation.

Related