ios - 如何通过 AppDelegate 升级使功能可用于大于 8 的 iOS

标签 ios swift core-data appdelegate

我从这个升级了我的 AppDelegate

// MARK: - Core Data stack

    lazy var applicationDocumentsDirectory: URL = {
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return urls[urls.count-1]
    }()

    lazy var managedObjectModel: NSManagedObjectModel = {
        let modelURL = Bundle.main.url(forResource: "TestProject", withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: modelURL)!
    }()

    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {

        // 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)

            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()
            } 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 10 通过 Swift 3 对核心数据进行编码

// MARK: - Core Data stack

    @available(iOS 10.0, *)
    lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: "TestProject")
        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

    @available(iOS 10.0, *)
    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)")
            }
        }
    }

但是当我在 View Controller 中编码时,我得到了适用于 iOS 10.0 的这些

@IBAction func saveBtnPressed(_ sender: AnyObject) {

        if #available(iOS 10.0, *) {
            let context =   (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

            let task = Task(context: context)
            task.taskDesc = goalText.text!
            task.taskImage = UIImagePNGRepresentation(choosenImage!)! as NSData?

        } else {
            // Fallback on earlier versions
        }
        //Save the data to coredata
        (UIApplication.shared.delegate as! AppDelegate).saveContext()
    }

无论如何,我可以使用带有 swift 3 语法的 iOS 10 并使功能适用于所有使用 iOS 8 及更高版本的设备。提前致谢

最佳答案

是的,您可以针对 iOSv8 发布 Swift 3 代码。下面是一个使用 Swift v2.3 的示例(v2.3 与 v3.0 是框架特征检测的一个不重要的区别):

convenience init(moc: NSManagedObjectContext) {
    if #available(iOS 10.0, *) {
        self.init(context: moc)
    }
    else {
        let name = NSStringFromClass(self.dynamicType)
        let entityName = name.componentsSeparatedByString(".").last!
        let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: moc)!
        self.init(entity: entity, insertIntoManagedObjectContext: moc)
    }
}

您必须问自己的真正问题是,为什么您要先于客户接受 Core Data 功能?

关于ios - 如何通过 AppDelegate 升级使功能可用于大于 8 的 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39810613/

相关文章:

ios - 使用JPG为我的UIImage正确命名

ios - 在 xcode 4 中自动化构建过程

ios - CoreData 根据不同的属性获取对象

iOS5 : Determine if core data method is running in an asynch dispatch queue?

ios - 栏中的ios后退按钮

ios - 如何以编程方式激活 "Installed"?

ios - 如何在 Swift 中设置 Google 跟踪代码管理器

swift - 如何检查 NSSound 是否在 Swift 中暂停

ios - 在 Swift 中迭代 NSLayoutConstraints 会出现 "[AnyObject] does not have a member named ' Generator'"错误

ios - 根据ios中的条件更新记录