coreData not fetching

My code below is using core data to add entities to a tableview. The problem is that when I hit the button to add a new entry the data is not displayed on the tableview. But if I quit the simulator and re install the app the entity is there. To get the entities displayed I have to enter it then reinstall the app to get the entity displayed.

                import UIKit
                import CoreData

        class ViewController: UIViewController {
            @IBOutlet var rot: UITableView!
            @IBOutlet var enterName: UITextField!
            var people : [NSManagedObject] = []
            override func viewDidLoad() {
                super.viewDidLoad()
                // Do any additional setup after loading the view, typically from a nib.
                showdata()
            }

            @IBAction func iDontLikeSchool(_ sender: Any) {

                if(enterName.text?.isEmpty)! {
                    alertmsg(name: "d")
                    showdata()
                } else {
                    saveData(name: enterName.text!)
                }}

            func alertmsg(name:String){
                let alert = UIAlertController(title: "D", message: "d", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }

            func saveData(name: String) {
                guard let appDelage = UIApplication.shared.delegate as? AppDelegate else {
                    return
                }
                let managedContext = appDelage.persistentContainer.viewContext

                let ee = NSEntityDescription.entity(forEntityName: "PersonalInfo", in: managedContext)!

                let person = NSManagedObject(entity : ee , insertInto: managedContext)
                person.setValue(name, forKey: "userName")

                do {
                    try managedContext.save()
                    people.append(person)
                    alertmsg(name: "saved")
                    enterName.text = ""
                }
                catch let err as NSError {
                    print("judo",err)
                }
                ///
            }

            func showdata() {
                guard let appDelage = UIApplication.shared.delegate as? AppDelegate else {
                    return
                }
                let managedContext = appDelage.persistentContainer.viewContext

                let fetchReuqst = NSFetchRequest<NSManagedObject>(entityName: "PersonalInfo")
                do {
                    people = try managedContext.fetch(fetchReuqst)

                    if people.count == 0 {

                    } else {

                    }}
                catch let err as NSError {
                    print("judo", err)
                }
                ///
            }
            }


        extension ViewController: UITableViewDataSource, UITableViewDelegate{
            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

                let cell = rot.dequeueReusableCell(withIdentifier: "Person")
                let personn = people[indexPath.row]

                cell?.textLabel?.text = personn.value(forKey: "userName") as? String

                return cell!

            }
            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                return people.count
            }
            func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            }
            }

@timswift Thanks very much for your question!

If you are using Core Data with a UITableView, then what you should do is incorporate NSFetchedResultsController to accomplish your task. NSFetchedResultsController updates your UITableView in real time, with any changes made in Core Data. :slight_smile:

On a side note, you should not be getting a reference to your ManagedObjectContext in your ViewController by using a reference to your AppDelegate. What you should do is instantiate a reference to your Core Data stack from your AppDelegate, and then from this reference, assign a value for the ManagedObjectContext to a ManagedObjectContext property belonging to the RootViewController.

I hope this helps!

All the best!

Hi @timswift, like @syedfa said, NSFetchedResultsController may benefit the use of Core Data and a tableview. Apple has great documentation on this, and it’s worth checking out! Apple Developer Documentation

This topic was automatically closed after 166 days. New replies are no longer allowed.