如何为NSPersistentContainer设置自定义商店URL

sha*_*ght 11 core-data swift3

如何将自定义store.sqlite URL设置为NSPersistentContainer?

我找到了一种丑陋的方式,继承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()
}
Run Code Online (Sandbox Code Playgroud)

}

有一个很好的方式吗?

背景:我需要保存到App Groups共享目录.

Tom*_*ton 20

你在NSPersistentStoreDescription课堂上这样做.它有一个初始化程序,您可以使用它来提供持久存储文件应该去的文件URL.

let description = NSPersistentStoreDescription(url: myURL)
Run Code Online (Sandbox Code Playgroud)

然后,使用NSPersistentContainer's persistentStoreDescriptions属性告诉它使用此自定义位置.

container.persistentStoreDescriptions = [description]
Run Code Online (Sandbox Code Playgroud)

注意:myURL必须提供完整的/path/to/model.sqlite,即使它还不存在.仅设置父目录不起作用.


blw*_*ers 8

扩展Tom的答案,当你NSPersistentStoreDescription出于任何目的使用时,一定要初始化,NSPersistentStoreDescription(url:)因为根据我的经验,如果你使用基本初始化程序NSPersistentStoreDescription()loadPersistentStores()基于该描述,它将在下次构建时覆盖现有的持久存储及其所有数据.跑.这是我用来设置URL和描述的代码:

let container = NSPersistentContainer(name: "MyApp")

let storeDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
let url = storeDirectory.appendingPathComponent("MyApp.sqlite")
let description = NSPersistentStoreDescription(url: url)
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
container.persistentStoreDescriptions = [description]

container.loadPersistentStores { (storeDescription, error) in
    if let error = error as? NSError {
        print("Unresolved error: \(error), \(error.userInfo)")
    }
}
Run Code Online (Sandbox Code Playgroud)