2017-04-27 173 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 
}