Swift Core Data - Change location of persistent store

372 views Asked by At

I have a swift program that reads CSV files and saves the data to a core data persistent store. I would like to change the location of the persistent store. Per Apple documentation it appears that I should be able to do so by overriding the default directory in a sub class of NSPersistentContainer. Below is my unsuccessful attempt. The Xcode error is "cannot call value of non-function type URL".

final class CoreDataContainer: NSPersistentContainer {
    let storePathURL: URL = URL(string: "file:///Users/Chris/Developer/Persistent Store")!
    override class func defaultDirectoryURL() -> URL {
        return super.defaultDirectoryURL()
            .absoluteURL(storePathURL)
   }
}
2

There are 2 answers

3
koen On

Not sure if this is what you are asking:

let storePathURL = // ...
let description = NSPersistentStoreDescription(url: storePathURL)
let container = NSPersistentContainer(name: "YourAppName")

container.persistentStoreDescriptions = [description]

container.loadPersistentStores { _, error in
   // ...
}
1
Chris On

Thank you for the input. I moved my folder into Downloads and added read/write access to it in the sandbox. Below is the updated code that works.

class CoreDataManager: ObservableObject {
    let persistentContainer: NSPersistentContainer
    static let shared = CoreDataManager()
    private init() {
        let storePathURL: URL = URL(fileURLWithPath: "/Users/Chris/Downloads/Persistent Store/Index Funds", isDirectory: false)
        let description = NSPersistentStoreDescription(url: storePathURL)
        persistentContainer = NSPersistentContainer(name: "Index Funds")
        persistentContainer.persistentStoreDescriptions = [description]
        persistentContainer.loadPersistentStores{ description, error in
            if let error = error {
                fatalError("Unable to initialize Core Data \(error)")
            }
        }
    } // end init
}