I'm new with ios dev and learning core data and stuck with updating tableview cells with reloaddata(). Here's the code in my GoalsVC:
import UIKit
import CoreData
//make app delegate accessible for all view controllers as in has core data things
let appDelegate = UIApplication.shared.delegate as? AppDelegate
class GoalsVC: UIViewController {
@IBOutlet weak var tableView: UITableView!
var goals: [Goal] = []
override func viewDidLoad() {
super.viewDidLoad()
//set tableview delegate and source so that it knows what its delegate its datasource is from otherwise it does not know where its getting information from
tableView.delegate = self
tableView.dataSource = self
tableView.isHidden = false
}
//need to think about when should we fetch the data. viewdidlaod only called once when the view is originally load. after we presented goalvc, creategoalvc on the top and dismiss them, viewdidload is not called bcs were just presenting a view on top of it and dismissing it.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.fetch { (complete) in
if complete {
if goals.count >= 1 {
//showing tableview or hide them depending if data is available or not
tableView.isHidden = false
} else {
tableView.isHidden = true
}
}
}
self.tableView.reloadData()
}
I don't know why self.tableView.reloadData() at the end there won't update the tableview.
Here's the code I made for saving data in FinishGoalVC if it helps to give a clearer view:
func save(completion: (_ finished: Bool) -> ()) {
guard let managedContext = appDelegate?.persistentContainer.viewContext else {
return
}
//accessing core data properties
let goal = Goal(context: managedContext)
goal.goalDescription = goalDescription
goal.goalType = goalType.rawValue
goal.goalCompletionValue = Int32(pointsTextField.text!)!
goal.goalProgress = Int32(0)
//using save in order to commit unsaved changes to the context parents store
do {
try managedContext.save()
completion(true)
} catch {
debugPrint("Could not save \(error.localizedDescription)")
completion(false)
}
}