简体   繁体   English

将核心数据数据库导入新项目

[英]Importing Core Data database to new project

I'm rewriting an application from Objective-C to Swift in a different project and I have a problem (fetch requests return empty results) with importing core data database, which in previous project were handled by MagicalRecord. 我正在将另一个项目中的应用程序从Objective-C重写到Swift,但是导入核心数据数据库时遇到问题(获取请求返回空结果),该问题在以前的项目中由MagicalRecord处理。

Here's what's I am doing: 这是我在做什么:

  1. Copied database model file to the new project. 将数据库模型文件复制到新项目。

  2. Add that model file to the Compile Sources and Copy Bundle Resources in Build Phases. 在构建阶段,将该模型文件添加到“编译源和副本捆绑资源”中。

  3. Changes entities code generation language from objc to swift inside model file. 将实体代码生成语言从objc更改为在模型文件内部快速转换。

  4. Create NSManagedObject subclasses 创建NSManagedObject子类

Things I've checked: 我检查过的事情:

  • PersistentStore's URL is the same (except sandbox's app identifier) as in the previous project. PersistentStore的URL与上一个项目中的URL相同(沙箱的应用程序标识符除外)。
  • Model file's name is the same as in the previous project. 模型文件的名称与上一个项目中的名称相同。
  • Target, scheme, project, and bundle id are the same as in the previous project. 目标,方案,项目和捆绑包ID与先前的项目相同。
  • Initialization of the whole core data stack (code below) works without errors. 整个核心数据堆栈(下面的代码)的初始化工作没有错误。

Here's how I initialize the stack (of course the strings here I've changed for known reasons, they are valid in the project): 这是我初始化堆栈的方式(当然,由于已知原因我更改了这里的字符串,它们在项目中有效):

    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
    }()

PersistentStore's url was NOT the same in the current and the previous project. PersistentStore的URL 没有被当前和以前的项目相同。

I thought it was but it wasn't. 我以为是,但不是。 One of the MagicalRecord's methods - NSPersistentStore.MR_defaultLocalStoreUrl - returned invalid NSURL. MagicalRecord的方法之一NSPersistentStore.MR_defaultLocalStoreUrl返回了无效的NSURL。

For the future generations - download your app's IPA via Xcode Device Manager and find out where its URL is manually! 对于子孙后代-通过Xcode设备管理器下载应用程序的IPA,并手动找到其URL!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM