带有预填充 .sqlite 的核心数据 (Swift3)

2024-05-24

目前,我正在对现有 iOS9 应用程序进行 Swift3 / iOS10 更新,该应用程序存储了欧洲各地约 10,000 个电动汽车充电点。到目前为止,我总是为应用程序提供预填充的数据库(.xcappdata 包中的 .sqlite、.sqlite-shm、.sqlite-wal 文件),但在当前版本中,Apple 引入了NS持久化容器 https://developer.apple.com/reference/coredata/nspersistentcontainer类,这使得它变得更加复杂。在我的 AppDelegate 类中,我实例化 NSPercientContainer 对象并将其传递给惰性变量,就像 Apple 在每个示例代码中所做的那样:

   lazy var stationDataPersistentContainer: NSPersistentContainer = {  
     let fileMgr = FileManager.default
     let destinationModel = NSPersistentContainer.defaultDirectoryURL()
     if !fileMgr.fileExists(atPath: destinationModel.appendingPathComponent("StationData.sqlite").path) {
         do {
             try fileMgr.copyItem(at: URL(fileURLWithPath: Bundle.main.resourcePath!.appending("/StationData.sqlite")), to: destinationModel.appendingPathComponent("/StationData.sqlite"))
             try fileMgr.copyItem(at: URL(fileURLWithPath: Bundle.main.resourcePath!.appending("/StationData.sqlite-shm")), to: destinationModel.appendingPathComponent("/StationData.sqlite-shm"))
             try fileMgr.copyItem(at: URL(fileURLWithPath: Bundle.main.resourcePath!.appending("/StationData.sqlite-wal")), to: destinationModel.appendingPathComponent("/StationData.sqlite-wal"))
         } catch {
             //
         }
     } else {
         //
     }
     /* 
     The persistent container for the application. This implementation 
     creates and returns a container, having loaded the store for the 
     application to it. This property is optional since there are legitimate 
     error conditions that could cause the creation of the store to fail. 
     */
    let container = NSPersistentContainer(name: "StationData")  
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in  
         if let error = error as NSError? {  
             /* 
              * Typical reasons for an error here include: 
              * The parent directory does not exist, cannot be created, or disallows writing. 
              * The persistent store is not accessible, due to permissions or data protection when the device is locked. 
              * The device is out of space. 
              * The store could not be migrated to the current model version. 
              * Check the error message to determine what the actual problem was. 
              */  
             fatalError("Unresolved error \(error), \(error.userInfo)")  
        }
    })  
    return container  
    }()

在 iOS 9 版本中,我将文件复制到适当的目录,如以下代码示例所示:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {  
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)  
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("StationData.sqlite")  
    let fileMgr = NSFileManager.defaultManager()  
    if !fileMgr.fileExistsAtPath(url.path!) {  
         do {  
              try fileMgr.copyItemAtPath(NSBundle.mainBundle().pathForResource("StationData", ofType: "sqlite")!, toPath: self.applicationDocumentsDirectory.URLByAppment("StationData.sqlite").path!)  
              try fileMgr.copyItemAtPath(NSBundle.mainBundle().pathForResource("StationData", ofType: "sqlite-shm")!, toPath: self.applicationDocumentsDirectory.URLByAppendingPathComponent("StationData.sqlite-shm").path!)  
              try fileMgr.copyItemAtPath(NSBundle.mainBundle().pathForResource("StationData", ofType: "sqlite-wal")!, toPath: self.applicationDocumentsDirectory.URLByAppendingPathComponent("StationData.sqlite-wal").path!)  
         } catch {  
              //  
         } do {  
              try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url,  
                                                       options: [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true])  
         } catch {  
              //  
         }  
    } else {  
         //  
    }  
    return coordinator
}() 

几天来我一直尝试将文件移动到正确的目录,该目录由NSPersistentContainer.defaultDirectoryURL() -> URL,但每次我收到错误时,该文件已经存在,因为我的 stationDataPersistentContainer 已经初始化,因此 NSPersistentContainer 有足够的时间来生成 sqlite* 文件。即使我尝试复制文件并在覆盖的 init() 函数中初始化 stationDataPersistentContainer,我也无法做到这一点。文档中是否有我遗漏或忽略的内容?这是将应用程序安装时的现有数据复制到 coredata 的最佳/正确/适当的方法。

附录:

仅供参考,我还可以将从 API 获取的 JSON 文件存储到文档目录中并运行 JSON 解析器,但这需要大量资源,尤其是时间!(这个问题也发布在苹果开发者论坛上,等待批准)


我就是这样做的:

lazy var persistentContainer: NSPersistentContainer = {

         let container = NSPersistentContainer(name: "app_name")

        let seededData: String = "app_name"
        var persistentStoreDescriptions: NSPersistentStoreDescription

        let storeUrl = self.applicationDocumentsDirectory.appendingPathComponent("app_name.sqlite")

        if !FileManager.default.fileExists(atPath: (storeUrl.path)) {
            let seededDataUrl = Bundle.main.url(forResource: seededData, withExtension: "sqlite")
            try! FileManager.default.copyItem(at: seededDataUrl!, to: storeUrl)

        }

        print(storeUrl)


        container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: storeUrl)]
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error {

                fatalError("Unresolved error \(error),")
            }
        })

         return container


    }()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带有预填充 .sqlite 的核心数据 (Swift3) 的相关文章

随机推荐

  • 使用 writeLines 将变量写入文件

    我发现此链接对于理解如何将行写入文件非常有帮助 将文本行写入 R 中的文件 https stackoverflow com questions 2470248 write lines of text to a file in r 不幸的是
  • Microsoft 身份 - 撤销授权

    我正在开发一个 NET 应用程序 它可以使用 Graph API 代表用户发送电子邮件 提示用户对应用程序进行授权 然后使用获取的访问令牌来调用 Graph API 刷新令牌用于在旧访问令牌过期时颁发新的访问令牌 如下所述 https le
  • 检查 Unix 消息队列是否为空

    谁能告诉我如何检查消息队列中是否有消息 消息队列是在基于Linux的操作系统中用C语言实现的 我只是想检查在特定时间消息队列中是否有消息 只需使用以下命令即可检查消息数量 如果有 msgctl 函数 并在返回时检查 msqid ds 结构
  • 使用 ssh-keygen 创建 SSH 密钥不会创建 .ssh 文件夹

    我正在尝试使用 msysgit 创建我的公共 私有 rsa 密钥对 我运行这个命令 ssh keygen C email protected cdn cgi l email protection t rsa 一切看起来都很好 我收到消息了
  • 如何使用 PowerShell 发布 Azure 网站 (xxx.azurewebsites.net)?

    我已经在一个文件夹中准备好了我的网站 我知道如何使用 Azure PowerShell 创建站点 在Azure管理门户中 我只需要通过FTP复制站点文件 但我不知道如何使用 PowerShell 将我的网站文件推送到 Azure 有人可以透
  • 设计 ASP.NET 图表控件的样式

    使用 which 是一个子集 http blogs msdn com alexgor archive 2008 11 07 microsoft chart control vs dundas chart control aspx of th
  • SQL Server 登录错误:用户“NT AUTHORITY\SYSTEM”登录失败

    我创建了一个名为 schoolPool 的应用程序池并将其分配给我的 Web 应用程序 该池的标识已设置为 LocalSystem 当我尝试从应用程序内访问数据库 即打开 SQL 连接 时 我总是收到以下错误 Login failed fo
  • 敏捷与迭代和增量开发之间的区别[关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 敏捷开发与迭代增量开发有什么区别 敏捷是否被视为迭代和增量 一些信息表明敏捷是最新的迭代和增量 我需要对此做出明确的澄清 迭代 你不可能一次性完
  • 在非 WordPress php 页面之外显示 WordPress 帖子

    我需要在非 WordPress php 页面中显示 WordPress 博客文章 我已经尝试过以下代码
  • 计算连续有多少次和的结果为正(或负)

    第一部分 我有一个包含财务数据的数据框 33023 行 这里是指向 数据 https mab to Ssy3TelRs https mab to Ssy3TelRs df open 是标题的价格 df close 是收盘价 我一直想看看标题
  • 为什么我的 Dockerfile CMD 不起作用?

    所以在我的 Dockerfile 的末尾我有这样的内容 WORKDIR home CMD django admin startproject whattt CMD bin bash 当我创建映像然后运行容器时 一切都按预期运行 没有错误 D
  • 按值或 ID 选择更多复选框

    我有这段代码 我想在其中创建一个切换按钮来选择 2 个或更多复选框 例如 意大利和德国 我正在尝试这段代码 但我无法让它工作 document on click checkbox button function e var checks i
  • 递归树遍历 - 如何跟踪递归级别?

    我基本上试图从表示树结构的多维数组构建 html ul li 嵌套列表 下面的代码工作正常 但我想改进它 我需要一种方法来跟踪递归级别 以便我可以将不同的类应用于不同的级别 向生成的输出添加缩进等 function buildTree tr
  • Android Studio 使用的默认 Android SDK 路径是什么?

    使用Android Studio下载Android SDK时 默认下载路径是什么 我有兴趣了解 Linux Mac 和 Windows 的路径 在网上搜索了一下 好像是这样的 Linux Android Sdk Mac Library An
  • C++ 中的转换错误

    有人可以帮我解决这个错误吗 我是 C 新手 看来错误就发生在一堆宏中 我能做什么来解决它 或者我怎样才能追踪到它的源头 我真的不明白这个错误 这是否意味着编译器尝试转换该方法void ReadCPUparameter to a LRESUL
  • 调用函数值[重复]

    这个问题在这里已经有答案了 可能的重复 函数提前触发 https stackoverflow com questions 12201816 function triggering early 我已经编写了这段代码 但是当我调用函数 test
  • 将自动复制位图转换为 Pillow 图像

    我正在使用 Autopy 和 Pillow 用 Python 开发屏幕抓取工具 是否可以将位图对象转换为 Pillow 图像对象 我当前的解决方案是将位图对象保存为图像文件 然后使用路径创建 Pillow 图像对象 这种方法是really由
  • 如何使用 numpy 在二维数组上执行最大/平均池化

    给定一个 2D M x N 矩阵和一个 2D 内核 K x L 我如何返回一个矩阵 该矩阵是使用图像上给定内核进行最大或平均池化的结果 如果可能的话我想使用 numpy 注意 M N K L 可以是偶数也可以是奇数 并且它们不需要彼此完全整
  • C中静态变量的初始化[重复]

    这个问题在这里已经有答案了 可能的重复 C中静态变量的初始化 https stackoverflow com questions 13251083 the initialization of static variable in c 我知道
  • 带有预填充 .sqlite 的核心数据 (Swift3)

    目前 我正在对现有 iOS9 应用程序进行 Swift3 iOS10 更新 该应用程序存储了欧洲各地约 10 000 个电动汽车充电点 到目前为止 我总是为应用程序提供预填充的数据库 xcappdata 包中的 sqlite sqlite