定义 Bundle.main.url 以使用 iOS 9 及更高版本的 Swift 4 的核心数据



我只是在学习核心数据,我需要为iOS 9iOS 10实现Core Data,因为我唯一的iPad测试设备是运行iOS 9.3.5的iPad3。我正在尝试 https://charleswilson.blog/2016/09/09/out-of-context-using-core-data-on-ios-9-3-and-10-0/遵循此解决方案(不确定我是否可以从链接粘贴整个代码),因为我无法从堆栈溢出实现其他解决方案。我不确定如果我做对了一件事:在lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator内部,有我在堆栈溢出的其他解决方案中看到的这个let modelURL = Bundle.main.url(forResource: modelName, withExtension: modelExtension)!,它们都被声明为forResource参数具有不同的String值,但withExtension:参数都具有相同的"momd"值。我实际上认为既然我使用的是.xcdatamodeld我应该为forResource参数输入数据模型名称,为withExtension:参数输入"xcdatamodeld",导致我的情况为:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let url = self.applicationDocumentsDirectory.appendingPathComponent("fix_it_shop").appendingPathExtension("xcdatamodeld")
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
let dict : [String : Any] = [NSLocalizedDescriptionKey        : "Failed to initialize the application's saved data" as NSString,
NSLocalizedFailureReasonErrorKey : "There was an error creating or loading the application's saved data." as NSString,
NSUnderlyingErrorKey             : error as NSError]
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
fatalError("Unresolved error (wrappedError), (wrappedError.userInfo)")
}
return coordinator
}()

是这样还是withExtension:参数与我的xcdatamodeld文件扩展名无关,我应该改用"momd"?我发现的类似问题指向了两个方向。非常感谢您对此的任何解释。

您应该使用"momd"作为模型的文件扩展名。 在 Xcode 编译过程中,您的 .xcdatamodeld 文件被编译成 .momd 文件,这是捆绑包中实际包含的内容。

但是,持久存储协调员定义中的url变量引用NSPersistentStore文件,对于 sqlite 存储,该文件的扩展名为".sqlite"。

最新更新