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

Posted

技术标签:

【中文标题】Swift 中适用于 iOS 9 和 iOS 10 的 CoreData 堆栈【英文标题】:CoreData Stack for both iOS 9 and iOS 10 in Swift 【发布时间】:2016-12-15 13:10:49 【问题描述】:

我正在尝试将 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 堆栈后,我发现新的 NSPersistentContainer 类可从 iOS 10 获得,因此我收到错误。

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

【问题讨论】:

Check this 为什么投反对票?感谢@shallowThought 的巨大努力和帮助......我正在搜索并认为我需要以某种方式将 NSPersistentContainer 组合到堆栈中,这就是为什么要问。 【参考方案1】:

这是对我有用的核心数据堆栈。我认为为了支持 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()
            
        
    

【讨论】:

【参考方案2】:

为 ios 9 和 10 使用下一个 Struct

这是用于上下文的,使用 nex 并将 ModelCoreData 替换为您的 CoreData 模型名称 存储.share.context

导入基础 导入核心数据

/// NSPersistentStoreCoordinator 扩展 扩展 NSPersistentStoreCoordinator

/// NSPersistentStoreCoordinator error types
public enum CoordinatorError: Error 
    /// .momd file not found
    case modelFileNotFound
    /// NSManagedObjectModel creation fail
    case modelCreationError
    /// Gettings document directory fail
    case storePathNotFound


/// Return NSPersistentStoreCoordinator object
static func coordinator(name: String) throws -> NSPersistentStoreCoordinator? 

    guard let modelURL = Bundle.main.url(forResource: name, withExtension: "momd") else 
        throw CoordinatorError.modelFileNotFound
    

    guard let model = NSManagedObjectModel(contentsOf: modelURL) else 
        throw CoordinatorError.modelCreationError
    

    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)

    guard let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else 
        throw CoordinatorError.storePathNotFound
    

    do 
        let url = documents.appendingPathComponent("\(name).sqlite")
        let options = [ NSMigratePersistentStoresAutomaticallyOption : true,
                        NSInferMappingModelAutomaticallyOption : true ]
        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
     catch 
        throw error
    

    return coordinator

结构存储

static var shared = Storage()

@available(iOS 10.0, *)
private lazy var persistentContainer: NSPersistentContainer = 
    let container = NSPersistentContainer(name: "ModelCoreData")
    container.loadPersistentStores  (storeDescription, error) in
        print("CoreData: Inited \(storeDescription)")
        guard error == nil else 
            print("CoreData: Unresolved error \(String(describing: error))")
            return
        
    
    return container
()

private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = 
    do 
        return try NSPersistentStoreCoordinator.coordinator(name: "ModelCoreData")
     catch 
        print("CoreData: Unresolved error \(error)")
    
    return nil
()

private lazy var managedObjectContext: NSManagedObjectContext = 
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
()

// MARK: Public methods

enum SaveStatus 
    case saved, rolledBack, hasNoChanges


var context: NSManagedObjectContext 
    mutating get 
        if #available(iOS 10.0, *) 
            return persistentContainer.viewContext
         else 
            return managedObjectContext
        
    


mutating func save() -> SaveStatus 
    if context.hasChanges 
        do 
            try context.save()
            return .saved
         catch 
            context.rollback()
            return .rolledBack
        
    
    return .hasNoChanges

func deleteAllData(entity: String)

    // let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = Storage.shared.context
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
    fetchRequest.returnsObjectsAsFaults = false

    do
    
        let results = try managedContext.fetch(fetchRequest)
        for managedObject in results
        
            let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
            managedContext.delete(managedObjectData)
        
     catch let error as NSError 
        print("Detele all data in \(entity) error : \(error) \(error.userInfo)")
    

【讨论】:

以上是关于Swift 中适用于 iOS 9 和 iOS 10 的 CoreData 堆栈的主要内容,如果未能解决你的问题,请参考以下文章

如何在Swift中初始化iOS 10和iOS 9.3的NSManagedObject子类

无效的 Swift 支持 - 适用于 iOS 9 的 Swift 2.0 项目,(Xcode build 7A220)

NSTimer - 适用于 iOS 10 但不适用于 iOS 9.3

Swift 和 TestFlight 适用于 iOS 8 但不适用于 iOS 7

Xcode 10:代码签名我的App + Framework失败,因为签署第三方依赖框架(PromiseKit)失败。适用于Xcode 9

适用于 iOS 的 Swift NativeModule 始终为空