教程_CoreData实例(二)_构建数据层
Swift教程_CoreData实例(五)_构建控制层(添加数据)
4.添加数据
我们自定义一个列表控制器PKOBookAddTableViewController,并应用到storyboard的添加显示view中,用来显示所选中的book的明细。通过点击PKOBooksTableViewController的Add按钮,跳转到PKOBookAddTableViewController页面,并通过Book对象来初始化列表。代码如下,注释非常详细,其中包含更新数据的部分代码,请结合下一小节的代码阅读:
PKOBookAddTableViewController继承于PKOBookDetailTableViewController,如下:
- import UIKit
- import CoreData
-
- class PKOBookAddTableViewController: PKOBookDetailTableViewController {
-
- var addObjectContext: NSManagedObjectContext!
- var delegate: PKOBooksTableViewController!
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
-
- self.setUpundoManager()
-
- self.editing = true
- }
-
- deinit{
- self.cleanUpUndoManager()
- }
-
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- }
-
- @IBAction func cancel(sender: AnyObject) {
- self.delegate!.addViewController(self, isSave: false)
- }
-
- @IBAction func save(sender: AnyObject) {
- self.delegate!.addViewController(self, isSave: true)
- }
-
- }
修改PKOBooksTableViewController,并添加对应addViewController方法,如下:
-
- override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
-
- if segue.identifier == "BookDetail" {
-
- var bookDetailTableViewController = segue.destinationViewController as PKOBookDetailTableViewController
- var currentRow = tableView.indexPathForSelectedRow()
- var book = self.fetchedResultsController?.objectAtIndexPath(currentRow!) as Book
- bookDetailTableViewController.book = book
- }
- else if segue.identifier == "BookAdd"{
- var navigationController = segue.destinationViewController as UINavigationController
- var bookAddTableViewController = navigationController.topViewController as PKOBookAddTableViewController
-
-
- var addContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
- addContext.parentContext = self.fetchedResultsController?.managedObjectContext
-
- var newBook = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext: addContext) as Book
- newBook.author = "Author1"
- newBook.title = "Titel1"
- newBook.theDate = NSDate()
-
- bookAddTableViewController.book = newBook
- bookAddTableViewController.addObjectContext = addContext
- bookAddTableViewController.delegate = self
- }
- }
-
-
-
- func addViewController(controller:PKOBookAddTableViewController, isSave: Bool){
-
- if isSave {
- NSLog("===dismissViewControllerAnimated 1===")
- var error: NSError? = nil
- if !controller.addObjectContext.save(&error) {
- NSLog("Unresolved error \(error), \(error!.userInfo)")
- abort()
- }
- NSLog("===dismissViewControllerAnimated 2===")
- if self.fetchedResultsController?.managedObjectContext.save(&error) == nil {
- NSLog("Unresolved error \(error), \(error!.userInfo)")
- abort()
- }
- }
- NSLog("===dismissViewControllerAnimated 3===")
- self.dismissViewControllerAnimated(true, completion: nil)
- }