Swift 3 从 appDelegate 中的 SQL 文件预加载

2024-01-07

我正在尝试 swift 3 转换。我正在我的 swift 2 项目中预加载来自 sql 文件的数据。我不确定如何在 swift 3.0 中实现此功能?下面是我的 swift 2 appDelegate 文件。在 swift 3 中,核心数据堆栈已经发生了足够的变化,我不知道在哪里尝试重用在 swift 2 中为我工作的相同代码。我正在使用的工作代码列在注释“为 SQLite 预加载添加”下。谢谢

    // MARK: - Core Data stack

lazy var applicationDocumentsDirectory: URL = {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "self.edu.SomeJunk" in the application's documents Application Support directory.
    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return urls[urls.count-1]
}()

lazy var managedObjectModel: NSManagedObjectModel = {
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
    let modelURL = Bundle.main.url(forResource: "ESLdata", withExtension: "momd")!
    return NSManagedObjectModel(contentsOf: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added 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.
    // Create the coordinator and store
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

    let url = self.applicationDocumentsDirectory.appendingPathComponent("ESLdata.sqlite")



    //ADDED FOR SQLITE PRELOAD
    // Load the existing database
    if !FileManager.default.fileExists(atPath: url.path) {
        let sourceSqliteURLs = [Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite")!,Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite-wal")!, Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite-shm")!]
        let destSqliteURLs = [self.applicationDocumentsDirectory.appendingPathComponent("ESLdata.sqlite"), self.applicationDocumentsDirectory.appendingPathComponent("ESLdata.sqlite-wal"), self.applicationDocumentsDirectory.appendingPathComponent("ESLdata.sqlite-shm")]
        for index in 0 ..< sourceSqliteURLs.count {
            do {
                try FileManager.default.copyItem(at: sourceSqliteURLs[index], to: destSqliteURLs[index])
            } catch {
                print(error)
            }
        }
    }
    // END OF ADDED CODE



    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, NSInferMappingModelAutomaticallyOption:true])
    } catch {
        // Report any error we got.
        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)
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }

    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

// MARK: - Core Data Saving support

func saveContext () {
    if managedObjectContext.hasChanges {
        do {
            try managedObjectContext.save()
            print("SAVED")
        } catch {
            print("Save Failed")

            let nserror = error as NSError
            NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
            abort()
        }
    }
}

以下是我尝试更新代码的内容,但没有成功:

func getDocumentsDirectory()-> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    /*
     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: "ESLdata")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             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)")
        }
        //ADDED FOR SQLITE PRELOAD

        let url = self.getDocumentsDirectory().appendingPathComponent("ESLdata.sqlite")
        // Load the existing database

        if !FileManager.default.fileExists(atPath: url.path) {
            let sourceSqliteURLs = [Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite")!,Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite-wal")!, Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite-shm")!]
            let destSqliteURLs = [self.getDocumentsDirectory().appendingPathComponent("ESLdata.sqlite"), self.getDocumentsDirectory().appendingPathComponent("ESLdata.sqlite-wal"), self.getDocumentsDirectory().appendingPathComponent("ESLdata.sqlite-shm")]
            for index in 0 ..< sourceSqliteURLs.count {
                do {
                    try FileManager.default.copyItem(at: sourceSqliteURLs[index], to: destSqliteURLs[index])
                } catch {
                    print(error)
                }
            }
        }
        // END OF ADDED CODE


    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

这似乎是我一直在寻找的解决方案。据我所知,到目前为止,它是有效的。并坚持适用于 iOS10 的新的精简格式核心数据堆栈。

func getDocumentsDirectory()-> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "ESLdata")

    let appName: String = "ESLdata"
    var persistentStoreDescriptions: NSPersistentStoreDescription

    let storeUrl = self.getDocumentsDirectory().appendingPathComponent("ESLData.sqlite")

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

    let description = NSPersistentStoreDescription()
    description.shouldInferMappingModelAutomatically = true
    description.shouldMigrateStoreAutomatically = true
    description.url = storeUrl

    container.persistentStoreDescriptions = [description]

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {

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

Swift 3 从 appDelegate 中的 SQL 文件预加载 的相关文章

  • 轻量级核心数据迁移后,如何为现有实体的新属性设置默认值?

    我已经成功完成了核心数据模型的轻量级迁移 我的自定义实体 Vehicle 收到了一个新属性 tirePressure 它是 double 类型的可选属性 默认值为 0 00 当从商店中获取 旧 车辆 在迁移发生之前创建的车辆 时 其 tir
  • 如何为现有核心数据实体添加更多属性?

    我有一个正在使用核心数据的项目 我需要向现有实体 列 添加更多属性 列 如果我手动将属性添加到数据模型应用程序崩溃 这是由于我用来将数据插入表的上下文保存之前 请帮助 谢谢 所以我的问题是我不知道这个持久存储协调器代码去了哪里 事实证明它是
  • 使用多个 DispatchQueue.main.async 查看冻结

    视图冻结而数据是获取并显示 以我的理解fetchBoard and initUserInfo 不要并行执行 因为视图仅在以下情况下加载fetchBoard 加载板 我担心如果使用DispatchQueue main async多次冻结视图
  • Swift 3 中的隐藏按钮

    我刚刚开始编码 我真的很想知道如何隐藏按钮 我想做的是当我按下按钮时 Start 我想让开始按钮和后退按钮消失 这是通过插座和操作完成的 我已经搜索了一下 但是当我想做的时候 它说do关键字应该指定一个语句块 我希望有人能帮助我 连接插座后
  • 将 Swift 类添加到具有多个目标的 Objective-C 项目

    我有一个现有的 Obj C 项目 其中包含许多共享相同 AppDelegate 的目标 我想桥接一个由选定目标使用的快速类 当我有一个目标时 我可以轻松地做到这一点 当我向项目添加 swift 文件时 我选择所需的目标并生成必要的 brid
  • 删除核心数据中的对象

    我的核心数据模型中有一个实体 如下所示 interface Selection NSManagedObject property nonatomic retain NSString book id property nonatomic re
  • 使用“对多”关系从 NSFetchedResultsController 派生 UITableView 部分

    我的核心数据模型如下所示 article lt gt gt category 是否可以远程使用NSFetchedResultsController生成一个看起来像这样的 UITableView Category 1 Article A Ar
  • CoreData 和 SwiftUI:环境中的上下文未连接到持久存储协调器

    我正在尝试通过构建一个作业管理应用程序来自学核心数据 我的代码构建良好 应用程序运行正常 直到我尝试将新分配添加到列表中 我收到这个错误Thread 1 EXC BREAKPOINT code 1 subcode 0x1c25719e8 在
  • 如何在 swift 3 中的表视图单元格中实现集合视图的分页?

    在这里 我有一个布局 其中我的表视图单元格之一由集合视图组成 在这个布局中我需要实现分页 但我无法使用func collectionView collectionView UICollectionView willDisplay cell
  • 如何将媒体附件添加到 iOS 10 应用程序中的推送通知中?

    有多个示例 您应该如何设置项目来添加使用 媒体附件 技术来显示图像的丰富通知 我已经阅读了其中的大部分内容 但我错过了一些内容 因为我的项目没有使用此有效负载显示任何丰富的通知 使用 APNS Tool 和 Boodle 进行测试 aps
  • EXC_BAD_INSTRUCTION 的 CoreData 错误(代码=EXC_I386_INVOP,子代码=0x0)

    当我打开并发调试开关 com apple CoreData ConcurrencyDebug 1 来跟踪 CoreData 的所有并发问题时 在调用 insertingNewObjectForEntityForName 时不断发生崩溃 Xc
  • 文档 Main.storyboard 需要 Xcode 8.0 或更高版本

    我下载了 Xcode beta 并打开了现有的项目 看看它如何与 Xcode 8 beta 一起使用 我从 Xcode 8 打开了 Storyboard 文件 现在 当我从 Xcode 7 3 打开项目时 我无法打开故事板文件 它给出了以下
  • 替换核心数据模型,无需迁移

    我已经相当广泛地改变了我的核心数据模型 关于如何将旧数据迁移到新模型中存在很多问题 但是我不需要迁移任何内容 我只想替换当前的 Core Data 实例 如何才能做到这一点 我假设您正在使用持久存储协调器NSSQLiteStoreType
  • Swift 3 中的 NSFetchedResultsController 删除缓存

    目前正在迁移到 swift 3 无法完全弄清楚解析器想要什么NSFetchedResultsController deleteCache withName rootCache 使用这种语法 我得到一个 Type String 构建时出现不符
  • 可以使用两个独立的 SQLite 数据库吗?

    我有一个 sqlite 数据库 其中存储用户定义的信息和用户只读的信息 我觉得将来可能需要修改只读信息 并且我不想进行整个数据迁移 有没有一种方法可以使用单独的 sqlite 数据库来存储只读信息 该数据库可以轻松替换 如果是这样 您能否就
  • Swift 3 中数组的 indexOf(_:) 方法的替换

    在我的项目 用 Swift 3 编写 中 我想使用从数组中检索元素的索引indexOf 方法 存在于 Swift 2 2 中 但我找不到任何替代方法 Swift 3 中是否有任何好的替代方法或类似的方法 Update 我忘记提及我想在自定义
  • Cocoa 基于文档的应用程序中的 MVC

    我目前正在对我的应用程序进行重构和重组 我意识到模型和视图及其控制器之间的一些分离已经减少 我希望进行一些清理 我的应用程序中使用了几个关键类 NSPersistentDocument NSWindowController 和模型类 NSP
  • 核心数据对多关系。它们是延迟加载吗?

    我在核心数据 适用于 iPhone 中有典型的模型 其中包含部门和员工 部门 gt gt 员工 我不想每次加载时都加载一个部门的所有员工 所以我想将员工创建为获取的属性 我想我可以定义一些像这样的谓词 employee deparmentI
  • NVActivityIndi​​catorView 仅适用于特定视图

    我正在使用这个库https github com ninjaprox NVActivityIndi catorView https github com ninjaprox NVActivityIndicatorView用于显示加载指示器
  • 在 swift3 中结合平移、alpha 和缩放动画

    我是 iOS Swift 开发的新手 我尝试将三个参数组合在一个动画中 但没有成功 我认为解决方案就在这里 Apple Dev Core 动画编程指南 https developer apple com library content do

随机推荐