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

How to make functionality to be available for iOS greater than 8 with AppDelegate upgrade

我从这个

升级了我的 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)")
            }
        }
    }

但是当我在视图控制器中编码时,我得到这些可用于 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()
    }

无论如何,我可以使用 iOS 10 和 swift 3 语法,并使所有使用 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 功能?