iOS 9 和 iOS 10 CoreData 同时
Posted
技术标签:
【中文标题】iOS 9 和 iOS 10 CoreData 同时【英文标题】:iOS 9 and iOS 10 CoreData simultaneously 【发布时间】:2017-04-27 07:26:56 【问题描述】:我有一个关于 Swift 3 与 Core Data 相关的问题。我正在使用 Xcode 8 在 Swift 中开发应用程序,我需要支持 ios 9 和 iOS10。问题是我不知道如何获取 AppDelegate 和 Context(用于存储和从我的实体获取数据)。我认为我的代码应该是这样的:
#if avaliable(iOS10,*)
// iOS 10 code
else
// iOS 9 code
但我不知道该怎么办。
有什么想法吗?
(不胜感激)
【问题讨论】:
为什么您认为在 iOS 9 和 10 中必须以不同方式处理“获取 AppDelegate 和上下文”? @Josep 问问自己核心数据在 iOS 9 和 10 之间的行为是否不同。然后问问自己需要区分的确切原因。然后更新你的 OP。例如,我有三个跨 iOS 6 到 10.2 的应用程序,在核心数据实现方面没有差异。 【参考方案1】:# iOS 9 和 iOS 10 Core Data 的 Swift 3 代码#
由于您需要 iOS 9 和 iOS 10 的核心数据代码,因此您不必使用 NSPersistentContainer
,因为它在 iOS 9 中不受支持,因此您必须改用旧方法
如果在创建项目时您还没有包含核心数据,而后来又想要包含它,请按照以下步骤操作:-
第 1 步。 转到 Build Phases
-> Link Binary with Library
-> click on + sign
-> Add CoreData.framework
第 2 步。现在转到file -> New File -> select Data Model
。
第 3 步。 现在您需要在 AppDelegate.swift
中编写一些代码来设置 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()
这就是你所有的 Core Data 都为 Swift 3 中的 iOS 9 和 iOS 10 准备好了。享受吧!!!
【讨论】:
为什么不使用 iOS 10 的新 iOS 10 堆栈而不是这个 一些项目同时兼容 ios 9 和 10【参考方案2】:如果你想支持 iOS9,那么最好不要使用任何新的 iOS10 东西。
暂时坚持使用 iOS9 API,当您最终放弃 iOS9 支持时,您可以重构代码以使用更新的方法。
编辑:为了清楚起见,所有 iOS9 代码在 iOS10 上都可以正常运行。你不需要在那里做任何特别的事情,它都是向后兼容的。
【讨论】:
我再次下载了Xcode 7(9月的Xcode8之前的最新版本)我已经基于Master-Detail模板创建了一个新项目。我没有改变任何东西。我已经用Xcode 8.2.1打开了项目,编辑器已经更新了,并且开始报出我无法纠正的错误。 请为您的问题创建一个新问题,cmets 不适合提问。【参考方案3】:CoreData 同时适用于 iOS9 和 iOS10
你可能需要它的人:
这是 2016 年 5 月最新 Xcode7(适用于 iOS9)版本的未经修改的 Master-Detail App 模板。我已使用当前最新的 Xcode(版本 8.2.1)对其进行了更新
使用此模板,您可以开发一个使用与 iOS9 和 iOS10 兼容的 CoreData 的应用程序,至少目前(2017 年 5 月)
AppDelegate.swift
//
// AppDelegate.swift
// trash
//
// Created by Markus on 22/05/17.
// Copyright © 2017 Markus. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let controller = masterNavigationController.topViewController as! MasterViewController
controller.managedObjectContext = self.managedObjectContext
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 throttle down OpenGL ES frame rates. 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 inactive 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)
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else return false
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else return false
if topAsDetailController.detailItem == nil
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
return false
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL =
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.senbei.trash" 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: "trash", 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()
MasterViewController.swift
//
// MasterViewController.swift
// trash
//
// Created by Markus on 22/05/17.
// Copyright © 2017 Markus. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate
var detailViewController: DetailViewController? = nil
var managedObjectContext: NSManagedObjectContext? = nil
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
override func viewWillAppear(_ animated: Bool)
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
func insertNewObject(_ sender: AnyObject)
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObject(forEntityName: entity.name!, into: context)
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(Date(), forKey: "timeStamp")
// Save the context.
do
try context.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.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
if segue.identifier == "showDetail"
if let indexPath = self.tableView.indexPathForSelectedRow
let object = self.fetchedResultsController.object(at: indexPath)
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int
return self.fetchedResultsController.sections?.count ?? 0
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let object = self.fetchedResultsController.object(at: indexPath) as! NSManagedObject
self.configureCell(cell, withObject: object)
return cell
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
// Return false if you do not want the specified item to be editable.
return true
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
if editingStyle == .delete
let context = self.fetchedResultsController.managedObjectContext
context.delete(self.fetchedResultsController.object(at: indexPath) as! NSManagedObject)
do
try context.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.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
func configureCell(_ cell: UITableViewCell, withObject object: NSManagedObject)
//cell.textLabel!.text = object.value(forKey: "timeStamp")!.description
cell.textLabel!.text = (object.value(forKey: "timeStamp")! as AnyObject).description
// MARK: - Fetched results controller
//var fetchedResultsController: NSFetchedResultsController
var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>
if _fetchedResultsController != nil
return _fetchedResultsController!
//let fetchRequest = NSFetchRequest()
//let fetchRequest = NSFetchRequest<Event>(entityName: "Event") //another alternative
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Event")
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entity(forEntityName: "Event", in: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
do
try _fetchedResultsController!.performFetch()
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.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
return _fetchedResultsController!
//var _fetchedResultsController: NSFetchedResultsController? = nil
var _fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>?
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
self.tableView.beginUpdates()
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType)
switch type
case .insert:
self.tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade)
case .delete:
self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade)
default:
return
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)
switch type
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .update:
self.configureCell(tableView.cellForRow(at: indexPath!)!, withObject: anObject as! NSManagedObject)
case .move:
tableView.moveRow(at: indexPath!, to: newIndexPath!)
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
self.tableView.endUpdates()
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController)
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
*/
DetailViewController.swift
//
// DetailViewController.swift
// trash
//
// Created by Markus on 22/05/17.
// Copyright © 2017 Markus. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController
@IBOutlet weak var detailDescriptionLabel: UILabel!
var detailItem: AnyObject?
didSet
// Update the view.
self.configureView()
func configureView()
// Update the user interface for the detail item.
if let detail = self.detailItem
if let label = self.detailDescriptionLabel
//label.text = detail.value(forKey: "timeStamp")!.description
label.text = (detail.value(forKey: "timeStamp")! as AnyObject).description
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
数据模型来源于模板,以及故事板。两者都没有修改。
【讨论】:
【参考方案4】:您可以通过执行以下操作来使用新 API 并从中受益:
var coreDataManager: CoreDataManagerProtocol!
#if available(iOS10,*)
coreDataManager = CoreDataManagerNewStack()
else
coreDataManager = CoreDataManagerOldStack()
然后你将新的 CoreData 与新堆栈一起实现到一个类中:
class CoreDataManagerNewStack: CoreDataManagerProtocol
var container: NSPersistentContainer
// etc
和上面贴上代码贴的旧的,用整个代码来生成堆栈
class CoreDataManagerOldStack: CoreDataManagerProtocol
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
()
// etc
【讨论】:
以上是关于iOS 9 和 iOS 10 CoreData 同时的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Swift 中为 iOS 10 和 iOS 9.3 初始化 NSManagedObject 子类
如何在Swift中初始化iOS 10和iOS 9.3的NSManagedObject子类