iOS & Swift 공부 - CoreData -> Read and Update Data from Core Data (Read & Update in CRUD)

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

iOS & Swift

목록 보기
94/107
post-thumbnail

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()
 }
profile
맛있는 iOS 프로그래밍

0개의 댓글