iOS & Swift 공부 - CoreData -> How to Save Data with Core Data (Create in CRUD)

김영채 (Kevin)·2021년 3월 16일
0

iOS & Swift

목록 보기
92/107
post-thumbnail

( ToDo App example )

  • We first have to modify the following code:
let newItem = Item()
  • First of all, we have to tap into the context variable from the AppDelegate.swift. But in order to do this, we first have to make an object of it. We use a singleton object for this.
let context = (UIApplication.shared.delegate as! AppDelegate),persistentContainer.viewContext
  • By executing the above code, we are getting the shared singleton object which corresponds to the current app as an object. Now, we have access to our AppDelegate as an object, which is imperative to using Core Data.
  • Now, we can write as follows :
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let newItem = Item(context: context)

  • In our saveItems( ) method, what we ultimately need to do is we need to be able to "commit" our context to permanent storage inside our persistentContainer.

  • In order to do that, we need to call "try context.save( )"

    → This basically transfers what's currently inside our staging area, the context, to our permanent data stores.

func saveItems() {
        
   do {
       try context.save()
    
    } catch {
       print("Error saving context \(error)")
    }

    self.tableView.reloadData()
}
  • So far, we set up the code to user Core Data for saving our new items that have been added.
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
        
        var textField = UITextField()
        
        let alert = UIAlertController(title: "Add New ToDo Item", message: "", preferredStyle: .alert)
        
        // The button you are going to press once you are done
        let action = UIAlertAction(title: "Add Item", style: .default) { (action) in
            
            // What will happen once the user clicks the Add Item button on our UIAlert
            
            let newItem = Item(context: self.context)
            newItem.title = textField.text!
            newItem.isDone = false          // must give value if not set to optional
            
            
            self.itemArray.append(newItem)
            self.saveItems()
            
        }
				alert.addTextField { (alertTextField) in
            alertTextField.placeholder = "Create new item"
            textField = alertTextField                      // Storing the same reference to a local variable accessible
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
        
        
    }
profile
맛있는 iOS 프로그래밍

0개의 댓글