同时使用iOS 9和iOS 10 CoreData [英] iOS 9 and iOS 10 CoreData simultaneously

查看:63
本文介绍了同时使用iOS 9和iOS 10 CoreData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于将Swift 3替换为Core Data的问题。我正在使用Xcode 8在Swift中开发一个应用程序,我需要支持iOS 9和iOS10。问题是我不知道如何获取AppDelegate和Context(用于存储和从我的实体获取数据)。我认为我的代码应该是这样的:

I have a question about Swift 3 releted with Core Data. I am developing an App in Swift with Xcode 8, and I need to support iOS 9 and iOS10. The problem is that I don't know how to get the AppDelegate and the Context (to use for store and get data from my Entities). I think my code should be something like this:

#if avaliable(iOS10,*)
{
     // iOS 10 code
} else
{
    // iOS 9 code
}

但是我不知道该怎么办。

But I don't know what to do.

有什么想法吗?

(将提供一些纠正方面的帮助)

(A small help in correction would be appreciated)

推荐答案

#Swift 3中用于核心数据的代码iOS 9和iOS 10#

由于您同时需要iOS 9和iOS 10的核心数据代码,因此不必使用 NSPersistentContainer ,因为它在iOS 9中不受支持,因此您必须改用旧方法

Since you want the core data code for both iOS 9 and iOS 10 then you don't have to use NSPersistentContainer as it not supported in iOS 9, so you have to use old method instead

如果在创建项目时您尚未包含核心数据,以后又想包含它,请执行以下步骤:-

If at the time of project creation you haven't included core data and later you want to include it, follow the following steps :-

步骤1。转到构建阶段-> 用库链接二进制文件-> 单击+符号-> 添加CoreData.framework

Step 1. Go to Build Phases -> Link Binary with Library -> click on + sign -> Add CoreData.framework

第2步。现在进入文件->新文件->选择数据模型

步骤3。现在,您需要在内编写一些代码AppDelegate.swift 进行设置:-

Step 3. Now you need to write some code inside AppDelegate.swift to get set go :-

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch. 
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        self.saveContext()

    }

    // MARK: - Core Data stack

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

    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: "Model", 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
        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()
            }
        }
    }
}

这就是您准备好的所有核心数据适用于Swift 3中的iOS 9和iOS10。请享受!!!

这篇关于同时使用iOS 9和iOS 10 CoreData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆