{"id":1174,"date":"2017-10-10T10:15:42","date_gmt":"2017-10-10T01:15:42","guid":{"rendered":"http:\/\/blue-bear.jp\/kb\/?p=1174"},"modified":"2017-10-10T10:15:42","modified_gmt":"2017-10-10T01:15:42","slug":"swift-add-delete-tasks-with-coredata","status":"publish","type":"post","link":"https:\/\/blue-bear.jp\/kb\/swift-add-delete-tasks-with-coredata\/","title":{"rendered":"[swift] Add \/ Delete Tasks with CoreData"},"content":{"rendered":"<p>for Add \/ Delete Tasks with CoreData, Refer below code<\/p>\n<p>with\u00a0Closure, Run Reload Table or fetch CoreData, Once Save\/Delete method has been completed<\/p>\n<p>Add CoreData after creating xcode Project without CoreData<\/p>\n<p>&nbsp;<\/p>\n<h2>Create CoreData<\/h2>\n<h3>Create Data Model File<\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-1169 size-medium\" src=\"http:\/\/blue-bear.jp\/kb\/wp-content\/uploads\/2017\/10\/\u30b9\u30af\u30ea\u30fc\u30f3\u30b7\u30e7\u30c3\u30c8-2017-10-10-9.51.45-300x135.png\" alt=\"\u30b9\u30af\u30ea\u30fc\u30f3\u30b7\u30e7\u30c3\u30c8 2017-10-10 9.51.45\" width=\"300\" height=\"135\" srcset=\"https:\/\/blue-bear.jp\/kb\/wp-content\/uploads\/2017\/10\/\u30b9\u30af\u30ea\u30fc\u30f3\u30b7\u30e7\u30c3\u30c8-2017-10-10-9.51.45-300x135.png 300w, https:\/\/blue-bear.jp\/kb\/wp-content\/uploads\/2017\/10\/\u30b9\u30af\u30ea\u30fc\u30f3\u30b7\u30e7\u30c3\u30c8-2017-10-10-9.51.45.png 734w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>Create new file with &#8220;New File&#8221; (CoreData -&gt; Data Model)<\/p>\n<p>Data Model\u00a0file name is &#8220;HitList&#8221;, then file named &#8220;HitList.xcdatamodeld&#8221; in xcode Project<\/p>\n<p>&nbsp;<\/p>\n<h3>Create Entity &amp; Attribute<\/h3>\n<p>in this case, Create\u00a0Entity (DB table in SQL) named &#8220;Person&#8221; and\u00a0Attribute (Column in SQL) named &#8220;Name&#8221; within\u00a0&#8220;Person&#8221; Entity<\/p>\n<p>with &#8220;Add Entity&#8221;, Create &#8220;Person&#8221; Entity<\/p>\n<p>with &#8220;Add Attribute&#8221;,\u00a0Create &#8220;Name&#8221;\u00a0Attribute<\/p>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-1170\" src=\"http:\/\/blue-bear.jp\/kb\/wp-content\/uploads\/2017\/10\/\u30b9\u30af\u30ea\u30fc\u30f3\u30b7\u30e7\u30c3\u30c8-2017-10-10-9.53.26-300x195.png\" alt=\"\u30b9\u30af\u30ea\u30fc\u30f3\u30b7\u30e7\u30c3\u30c8 2017-10-10 9.53.26\" width=\"300\" height=\"195\" srcset=\"https:\/\/blue-bear.jp\/kb\/wp-content\/uploads\/2017\/10\/\u30b9\u30af\u30ea\u30fc\u30f3\u30b7\u30e7\u30c3\u30c8-2017-10-10-9.53.26-300x195.png 300w, https:\/\/blue-bear.jp\/kb\/wp-content\/uploads\/2017\/10\/\u30b9\u30af\u30ea\u30fc\u30f3\u30b7\u30e7\u30c3\u30c8-2017-10-10-9.53.26-768x499.png 768w, https:\/\/blue-bear.jp\/kb\/wp-content\/uploads\/2017\/10\/\u30b9\u30af\u30ea\u30fc\u30f3\u30b7\u30e7\u30c3\u30c8-2017-10-10-9.53.26-1024x666.png 1024w, https:\/\/blue-bear.jp\/kb\/wp-content\/uploads\/2017\/10\/\u30b9\u30af\u30ea\u30fc\u30f3\u30b7\u30e7\u30c3\u30c8-2017-10-10-9.53.26.png 1240w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>&nbsp;<\/p>\n<h2>AppDelegate.swift<\/h2>\n<p>Add below code into AppDelegate.swift<\/p>\n<ul>\n<li>when create project with CoreData, these code will be generate automatically<\/li>\n<\/ul>\n<p>Should add\u00a0Data Model name into on &#8220;NSPersistentContainer&#8221;<\/p>\n<pre class=\"\">\/\/ MARK: - Core Data stack\r\n\r\n  lazy var persistentContainer: NSPersistentContainer = {\r\n    \/*\r\n     The persistent container for the application. This implementation\r\n     creates and returns a container, having loaded the store for the\r\n     application to it. This property is optional since there are legitimate\r\n     error conditions that could cause the creation of the store to fail.\r\n     *\/\r\n    let container = NSPersistentContainer(name: \"<span style=\"color: #ff0000;\">HitList<\/span>\")\r\n    container.loadPersistentStores(completionHandler: { (storeDescription, error) in\r\n      if let error = error as NSError? {\r\n        \/\/ Replace this implementation with code to handle the error appropriately.\r\n        \/\/ fatalError() 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.\r\n\r\n        \/*\r\n         Typical reasons for an error here include:\r\n         * The parent directory does not exist, cannot be created, or disallows writing.\r\n         * The persistent store is not accessible, due to permissions or data protection when the device is locked.\r\n         * The device is out of space.\r\n         * The store could not be migrated to the current model version.\r\n         Check the error message to determine what the actual problem was.\r\n         *\/\r\n        fatalError(\"Unresolved error \\(error), \\(error.userInfo)\")\r\n      }\r\n    })\r\n    return container\r\n  }()\r\n\r\n  \/\/ MARK: - Core Data Saving support\r\n\r\n  func saveContext () {\r\n    let context = persistentContainer.viewContext\r\n    if context.hasChanges {\r\n      do {\r\n        try context.save()\r\n      } catch {\r\n        \/\/ Replace this implementation with code to handle the error appropriately.\r\n        \/\/ fatalError() 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.\r\n        let nserror = error as NSError\r\n        fatalError(\"Unresolved error \\(nserror), \\(nserror.userInfo)\")\r\n      }\r\n    }\r\n  }  \r\n<\/pre>\n<h2>ViewController.swift<\/h2>\n<p>Install TableView on ViewController<\/p>\n<p>with\u00a0fetchPersonData,\u00a0retrieve\u00a0NSManagedObject from CoreDate, then add\u00a0NSManagedObject into Array named &#8220;people&#8221;<\/p>\n<p>NSManagedObject is &#8220;Dictionary&#8221; type. You can access each element with below code<\/p>\n<blockquote><p>cell.textLabel?.text = person.value(forKeyPath: &#8220;name&#8221;) as? String<\/p><\/blockquote>\n<pre class=\"\">import UIKit\r\nimport CoreData\r\n\r\nclass ViewController: UIViewController {\r\n\r\n  @IBOutlet weak var tableView: UITableView!\r\n  var people: [NSManagedObject] = []\r\n\r\n  override func viewDidLoad() {\r\n    super.viewDidLoad()\r\n\r\n    title = \"The List\"\r\n    tableView.register(UITableViewCell.self,\r\n                       forCellReuseIdentifier: \"Cell\")\r\n  }\r\n\r\n  override func viewWillAppear(_ animated: Bool) {\r\n    super.viewWillAppear(animated)\r\n    \r\n    fetchPersonData(){\r\n      self.tableView.reloadData()\r\n    }\r\n  }\r\n\r\n  @IBAction func addName(_ sender: UIBarButtonItem) {\r\n\r\n    let alert = UIAlertController(title: \"New Name\",\r\n                                  message: \"Add a new name\",\r\n                                  preferredStyle: .alert)\r\n\r\n    let saveAction = UIAlertAction(title: \"Save\", style: .default) { [unowned self] action in\r\n\r\n      guard let textField = alert.textFields?.first,\r\n        let nameToSave = textField.text else {\r\n          return\r\n      }\r\n\r\n      self.saveName(name: nameToSave){\r\n        self.fetchPersonData() {\r\n          self.tableView.reloadData()\r\n        }\r\n      }\r\n    }\r\n\r\n    let cancelAction = UIAlertAction(title: \"Cancel\",\r\n                                     style: .default)\r\n\r\n    alert.addTextField()\r\n\r\n    alert.addAction(saveAction)\r\n    alert.addAction(cancelAction)\r\n\r\n    present(alert, animated: true)\r\n  }\r\n\r\n  func save(name: String) {\r\n    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {\r\n      return\r\n    }\r\n\r\n    let managedContext = appDelegate.persistentContainer.viewContext\r\n\r\n    let entity = NSEntityDescription.entity(forEntityName: \"Person\",\r\n                                            in: managedContext)!\r\n\r\n    let person = NSManagedObject(entity: entity,\r\n                                 insertInto: managedContext)\r\n\r\n    person.setValue(name, forKeyPath: \"name\")\r\n\r\n    do {\r\n      try managedContext.save()\r\n      people.append(person)\r\n    } catch let error as NSError {\r\n      print(\"Could not save. \\(error), \\(error.userInfo)\")\r\n    }\r\n  }\r\n}\r\n\r\n\/\/ MARK: - UITableViewDataSource\r\nextension ViewController: UITableViewDataSource {\r\n\r\n  func tableView(_ tableView: UITableView,\r\n                 numberOfRowsInSection section: Int) -&gt; Int {\r\n    return people.count\r\n  }\r\n\r\n  func tableView(_ tableView: UITableView,\r\n                 cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {\r\n\r\n    let person = people[indexPath.row]\r\n    let cell = tableView.dequeueReusableCell(withIdentifier: \"Cell\",\r\n                                             for: indexPath)\r\n    cell.textLabel?.text = person.value(forKeyPath: \"name\") as? String\r\n    return cell\r\n  }\r\n  \r\n  \r\n  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {\r\n    if editingStyle == .delete {\r\n      let person = people[indexPath.row]\r\n\r\n      deleteName(managedObject: person){\r\n        self.fetchPersonData(){\r\n          self.tableView.deleteRows(at: [indexPath], with: .fade)\r\n          self.tableView.reloadData()\r\n        }\r\n      }\r\n\r\n    }\r\n  }\r\n  \r\n}\r\n\r\n\r\n\/\/MARK: Controll CoreData\r\n\r\nextension ViewController {\r\n  func saveName(name: String, completion: (()-&gt;Void)?) {\r\n    \r\n    guard let appDelegate =\r\n      UIApplication.shared.delegate as? AppDelegate else {\r\n        return\r\n    }\r\n    \r\n    let managedContext =\r\n      appDelegate.persistentContainer.viewContext\r\n    \r\n    let entity =\r\n      NSEntityDescription.entity(forEntityName: \"Person\",\r\n                                 in: managedContext)!\r\n    \r\n    let person = NSManagedObject(entity: entity,\r\n                                 insertInto: managedContext)\r\n    \r\n    person.setValue(name, forKeyPath: \"name\")\r\n    \r\n    do {\r\n      try managedContext.save()\r\n      completion?()\r\n    } catch let error as NSError {\r\n      print(\"Could not save. \\(error), \\(error.userInfo)\")\r\n    }\r\n  }\r\n  \r\n  func fetchPersonData(completion: (()-&gt;Void)?) {\r\n    \r\n    guard let appDelegate =\r\n      UIApplication.shared.delegate as? AppDelegate else {\r\n        return\r\n    }\r\n    \r\n    let managedContext =\r\n      appDelegate.persistentContainer.viewContext\r\n    \r\n    let fetchRequest =\r\n      NSFetchRequest(entityName: \"Person\")\r\n    \r\n    do {\r\n      people = try managedContext.fetch(fetchRequest)\r\n      completion?()\r\n    } catch let error as NSError {\r\n      print(\"Could not fetch. \\(error), \\(error.userInfo)\")\r\n    }\r\n  }\r\n  \r\n  func updateName(managedObject: NSManagedObject, newName: String, completion: (()-&gt;Void)?) {\r\n    \r\n    guard let appDelegate =\r\n      UIApplication.shared.delegate as? AppDelegate else {\r\n        return\r\n    }\r\n    \r\n    let managedContext =\r\n      appDelegate.persistentContainer.viewContext\r\n    \r\n    do {\r\n      managedObject.setValue(newName, forKey: \"name\")\r\n      \r\n      try managedContext.save()\r\n      completion?()\r\n    } catch {\r\n      \r\n    }\r\n  }\r\n  func deleteName(managedObject: NSManagedObject, completion: (()-&gt;Void)?) {\r\n    \r\n    guard let appDelegate =\r\n      UIApplication.shared.delegate as? AppDelegate else {\r\n        return\r\n    }\r\n    \r\n    let managedContext =\r\n      appDelegate.persistentContainer.viewContext\r\n    \r\n    do {\r\n      managedContext.delete(managedObject)\r\n      print(\"deleteName\")\r\n      try managedContext.save()\r\n      completion?()\r\n    } catch {\r\n      print(\"deleteName error\")\r\n    }\r\n  }\r\n}\r\n\r\n\r\n\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>for Add \/ Delete Tas<\/p>\n","protected":false},"author":1,"featured_media":88,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[13],"tags":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/blue-bear.jp\/kb\/wp-json\/wp\/v2\/posts\/1174"}],"collection":[{"href":"https:\/\/blue-bear.jp\/kb\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blue-bear.jp\/kb\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blue-bear.jp\/kb\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blue-bear.jp\/kb\/wp-json\/wp\/v2\/comments?post=1174"}],"version-history":[{"count":1,"href":"https:\/\/blue-bear.jp\/kb\/wp-json\/wp\/v2\/posts\/1174\/revisions"}],"predecessor-version":[{"id":1175,"href":"https:\/\/blue-bear.jp\/kb\/wp-json\/wp\/v2\/posts\/1174\/revisions\/1175"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blue-bear.jp\/kb\/wp-json\/wp\/v2\/media\/88"}],"wp:attachment":[{"href":"https:\/\/blue-bear.jp\/kb\/wp-json\/wp\/v2\/media?parent=1174"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blue-bear.jp\/kb\/wp-json\/wp\/v2\/categories?post=1174"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blue-bear.jp\/kb\/wp-json\/wp\/v2\/tags?post=1174"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}