Search code examples
ioscore-data

NSPersistentContainer / Core Data / ReadOnly store


I just set up a readonly data-store on Core Data. It works but the compiler has a complain about it and I would like to know how to fix this.

Here the relevant code as I modified it after the Xcode automatically generated template.

lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "MyApp")

    let appName: String = "MyApp",
    storeUrl = Bundle.main.url(forResource: appName, withExtension: "sqlite")
    var persistentStoreDescriptions: NSPersistentStoreDescription

    let description = NSPersistentStoreDescription()
    description.shouldInferMappingModelAutomatically = true
    description.shouldMigrateStoreAutomatically = true
    description.url = storeUrl

    container.persistentStoreDescriptions = [description]

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

Now this is the message I get from the compiler:

[error] CoreData: error: Attempt to add read-only file at path ...../MyApp.app/MyApp.sqlite read/write. Adding it read-only instead. This will be a hard error in the future; you must specify the NSReadOnlyPersistentStoreOption.

How do I set this option so the compiler is happy?


Solution

  • Set the option in the description

    description.setOption(NSNumber(value: true), forKey: NSReadOnlyPersistentStoreOption)
    

    By the way: The variable persistentStoreDescriptions is unused.