表格视图中未获取核心数据

时间:2018-01-22 16:39:00

标签: ios swift uitableview core-data fetch

下面的代码是使用核心数据将实体添加到tableview。问题是,当我点击按钮添加新条目时,数据不会显示在tableview上。但是,如果我退出模拟器并重新安装应用程序,那么实体就在那里。要显示实体,我必须输入它,然后重新安装应用程序以显示实体。

  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) {
        }
        }

1 个答案:

答案 0 :(得分:0)

条目未显示的原因是您没有告诉视图您的模型已更改,因此它不会刷新自身。 tableView在viewDidLoad上呈现一次,这就是为什么在新加载视图后(在应用程序重新启动之后)正确显示数据的原因。

要解决此问题,请将viewController的tableView保存为属性(如果使用Storyboard,则保留@IBOutlet)并调用

tableView.reloadData()

更改数据后,在您的情况下,例如在func showData()这样的结尾。

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 {
            //sth
        } else {
            // sth
        }
    } catch let err as NSError {
        print("judo", err)
    }
    tableView.reloadData()
}