2017-04-27 110 views
2

我有一个关于Swift 3与Core Data关联的问题。我正在用Xcode 8在Swift上开发一个应用程序,并且我需要支持iOS 9和iOS 10。问题是我不知道如何获得AppDelegate和Context(用于存储和从我的实体获取数据)。我认为我的代码应该是这样的:iOS 9和iOS 10 CoreData同时

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

但我不知道该怎么做。

有什么想法?

(在修正一个小的帮助,将不胜感激)

+0

为什么在iOS 9和10中必须以不同的方式处理“获取AppDelegate和上下文”? – shallowThought

+0

@Josep问自己核心数据在iOS 9和10之间的行为是否有所不同。然后问自己需要区分的确切原因。然后更新你的OP。例如,我有三个跨iOS 6到10.2的应用程序,在核心数据实施方面没有任何差异。 – andrewbuilder

回答

0

#代码在斯威夫特3核心数据量。iOS 9和iOS 10#

既然你想为这两个iOS的核心数据代码

9和iOS 10,那么您不必使用NSPersistentContainer,因为它在iOS 9中不受支持,因此您必须使用旧方法代替

如果在项目创建时未包含核心数据,想要包含它,请按照以下步骤操作: -

第1步:进入Build Phases - >Link Binary with Library - >click on + sign - >Add CoreData.framework enter image description here

第2步:现在得file -> New File -> select Data Model

第3步:现在,你需要写里面AppDelegate.swift一些代码来获取设置去 -

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() 
      } 
     } 
    } 
} 

这就是你所有的核心数据是准备在斯威夫特3两的iOS 9和iOS 10。请享用 !!!

+0

谢谢你!适合我! –

+0

为什么不使用iOS 10的新iOS 10堆栈? –

+0

有些项目兼容ios 9和10以及 –

0

如果你想支持iOS9,那么最好的办法是不要使用任何新的iOS10的东西。

现在坚持使用iOS9 API,未来当您最终放弃iOS9支持时,您可以重构代码以使用更新的方法。

编辑:只需要清楚,iOS9的所有代码都可以在iOS10上正常运行。你不需要做任何特别的事情,它都是向后兼容的。

+0

我已经下载了Xcode 7(9月Xcode8之前的最新版本) 我已经创建一个基于Master-Detail模板的新项目。我没有改变任何东西。 我用Xcode 8.2.1打开了项目,编辑器已经更新了它,并且已经开始给出我无法修正的错误。 – Markus

+0

请为您的问题创建一个新问题,评论不是正确的地方要问。 – trapper

+0

你说得对,我会把它放在心上! –

0

CoreData的iOS9同时

对于您可能需要谁iOS10:

这是自2016年五月我的最新Xcode7(用于iOS9)释放未修改的主从应用程序模板已经与使用CoreData兼容iOS9和iOS10,至少现在(五月2017)目前的最新的Xcode(版本8.2.1)

有了这个模板,你可以可一个应用

更新它

AppDelegate。迅速

// 
// 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. 
} 


} 

数据模型从模板,以及故事板原。两者都没有修改。 Data model screenshot

+0

感谢Markus! –

0

您可以使用新的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 
}