ios - Swift 中适用于 iOS 9 和 iOS 10 的 CoreData 堆栈

标签 ios swift database core-data

我正在尝试将 Core Data 添加到支持 iOS 9+ 的现有项目中。

我添加了 Xcode 生成的代码:

// MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {

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

                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

在 Xcode 中生成标准 CoreData Stack 后,我发现新类 NSPersistentContainer 可从 iOS 10 获得,结果我收到错误。

正确的 CoreData Stack 应该如何支持 iOS 9 和 10?

最佳答案

这是对我有用的核心数据堆栈。我认为为了支持 iOS 10,我需要实现 NSPersistentContainer 类,但我发现带有 NSPersistentStoreCoordinator 的旧版本也能正常工作。

您必须更改模型 (coreDataTemplate) 和项目 (SingleViewCoreData) 的名称。

swift 3:

// MARK: - CoreData Stack

    lazy var applicationDocumentsDirectory: URL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "com.cadiridris.coreDataTemplate" 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: "coreDataTemplate", 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("SingleViewCoreData.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: nil)
        } 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
        managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        return managedObjectContext
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        if managedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            } catch {
                // Replace this implementation 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.
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }
        }
    }

关于ios - Swift 中适用于 iOS 9 和 iOS 10 的 CoreData 堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41165025/

相关文章:

ios - Objective-C - 无法通过 Firebase 动态链接打开我的应用程序

swift - 我可以在 UIPageViewController 中隐藏页面指示器吗?

sql - 更新 MySQL 中的关联表

android - SQLiteOpenHelper - 在 SD 卡上创建数据库

ios - UIImage 的最大宽度?

ios - 单元格高度 : Thread 1: Fatal error: Index out of range when pulling up data in UITableView

iphone - 固定 UITableView 的高度

swift - 如何更改导航 Controller 标题

ios - UIView - 带有持续时间的动画似乎忽略了持续时间

java - 使用 LIKE 仅搜索包含年份和月份的日期