iOSおよびSWIFTラーニング-CoreData->Core Dataからのデータの読み取りと更新(CRUDのRead&Update)


Reading Data from Core Data (Read in CRUD)
  • How can we load up items from our system container?
  • ex. Entire code
    func loadItems() {
    
        let request: NSFetchRequest<Item> = Item.fetchRequest()
        do {
           itemArray = try context.fetch(request)
        } catch {
            print("Error fetching data from context \(error)")
        }
    }
    // Used do-catch statement as fetch() can return an error
  • context.fetch(request) → Since we cannot directly fetch data from the Persistent Container, we use this method. The context, or the staging area, fetches data from the Persistent Container using NSFetchRequest, which returns an array of Item, which we declared earlier.
  • Note that you have to specify the data type of the "request". This is the very few cases where you have to specify the data type in Swift.
  • Updating Data from Core Data (Update in CRUD)
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            
        itemArray[indexPath.row].isDone = !itemArray[indexPath.row].isDone
        saveItems()
        
        tableView.deselectRow(at: indexPath, animated: true)    // cell 을 누르자마자 deselect 되는 애니메이션이 나올 수 있도록
            
    }
    
    func saveItems() {
            
        do {
            try context.save()
        
        } catch {
            print("Error saving context \(error)")
        }
    
        self.tableView.reloadData()
     }