我只是在学习核心数据,我需要为iOS 9
和iOS 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"。