Search code examples
core-dataswift3

How to set a custom store URL for NSPersistentContainer


How can I set a custom store.sqlite URL to NSPersistentContainer?

I have found an ugly way, subclassing NSPersistentContainer:

final public class PersistentContainer: NSPersistentContainer {
private static var customUrl: URL?

public init(name: String, managedObjectModel model: NSManagedObjectModel, customStoreDirectory baseUrl:URL?) {
    super.init(name: name, managedObjectModel: model)
    PersistentContainer.customUrl = baseUrl
}

override public class func defaultDirectoryURL() -> URL {
    return (customUrl != nil) ? customUrl! : super.defaultDirectoryURL()
}

}

Is there a nice way?

Background: I need to save to an App Groups shared directory.


Solution

  • You do this with the NSPersistentStoreDescription class. It has an initializer which you can use to provide a file URL where the persistent store file should go.

    let description = NSPersistentStoreDescription(url: myURL)
    

    Then, use NSPersistentContainer's persistentStoreDescriptions attribute to tell it to use this custom location.

    container.persistentStoreDescriptions = [description]
    

    Note: myURL must provide the complete /path/to/model.sqlite, even if it does not exist yet. It will not work to set the parent directory only.