John Carter
John Carter

Reputation: 1

UITableView with Xcode, Fetching CoreData Problem

I have been working for a project but stuck on how to retrieve CoreData to my Table View. This is my code:

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

func loadData(){
       let requestData: NSFetchRequest<Person> = Person.fetchRequest()
       do {
           try
               personArr = context.fetch(requestData)
               try context.save()
          } catch {print ("Error retrieving data request \(error)")
           self.tableView.reloadData()
       }
   }

//  let DVC = segue.destination as! addPersonController
// numberOfRowsInSection ... cellForRowAt
// let cell = tableView.dequeueReusableCell(withIdentifier: "personCell", for: indexPath)
// cell.textLabel?.text = itemArray[indexPath.row].title > let person = personArr[indexPath.row]

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      if(tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark)
       {tableView.cellForRow(at: indexPath)?.accessoryType = .none
           personArr[indexPath.row].finish = false
           //cell.accessoryType = .checkmark //forRaw
       }
        tableView.deselectRow(at: indexPath, animated: true) //not selected
        savePerson()
       // let myPerson = PersonArr[indexPath.row].name
       // performSegue(withIdentifier: "personSegue", sender: myPerson)
}

Here is just an example of some function that I applied. my concern is at fetching data to personArr that is not been fetching as expected. Any ideas?

Upvotes: 0

Views: 50

Answers (1)

vadian
vadian

Reputation: 285290

A closer look at the code reveals that you are reloading the table view in the catch scope which is almost never going to happen.

Move the line into the do scope and delete the pointless line to save the context

func loadData(){
   let requestData: NSFetchRequest<Person> = Person.fetchRequest()
   do {
       personArr = try context.fetch(requestData)
       self.tableView.reloadData()
   } catch {
       print ("Error retrieving data request \(error)")
   }
}

Upvotes: 1

Related Questions