我在一个不同的项目中将一个应用程序从Objective-C重写为Swift,并且我有一个问题(获取请求返回空结果),导入核心数据数据库,在之前的项目中由MagicalRecord处理。
这就是我在做什么:
将数据库模型文件复制到新项目中。
将该模型文件添加到构建阶段的编译源和复制包资源中。
将实体代码生成语言从objc更改为swift内部模型文件。
创建NSManagedObject子类
我检查过的事情:
这是我如何初始化堆栈(当然这里的字符串我已经因为已知的原因而改变了,它们在项目中是有效的):
lazy var applicationDocumentsDirectory: URL = {
let urls = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
var applicationDocumentsDirectoryRaw = urls[urls.count-1]
applicationDocumentsDirectoryRaw.appendPathComponent("App_Name", isDirectory: true)
return applicationDocumentsDirectoryRaw
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: "Model_Name", withExtension: "momd")!
return NSManagedObjectModel.init(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("CoreDataStore.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: [NSMigratePersistentStoresAutomaticallyOption: true])
} catch {
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
答案 0 :(得分:0)
PersistentStore的网址在当前和之前的项目中 NOT 相同。
我以为是,但事实并非如此。
MagicalRecord的一种方法 - NSPersistentStore.MR_defaultLocalStoreUrl
- 返回了无效的NSURL。
对于后代 - 通过Xcode设备管理器下载您应用的IPA,并找出其URL的手动位置!