当我添加新值时,如何从另一个viewController重新加载tableview?

时间:2018-03-11 11:14:33

标签: ios swift uitableview

我已经在StackOverFlow上尝试了与我相同的问题,但它没有用。

这是我的故事板。

enter image description here

以下是我的var people = [Person]() @IBOutlet weak var patientView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let fetchReq: NSFetchRequest<Person> = Person.fetchRequest() do{ let people = try PersistenceService.context.fetch(fetchReq) self.people = people self.patientView.reloadData() }catch{ } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) patientView.reloadData() }

的代码
TableViewController

这是我的var people = [Person]() @IBOutlet weak var patientName: UITextField! @IBOutlet weak var patientAge: UITextField! @IBAction func btnAdd(_ sender: UIButton) { let person = Person(context: PersistenceService.context) person.name = patientName.text person.age = Int16(patientAge.text!)! PersistenceService.saveContext() self.people.append(person) } @IBAction func btnClear(_ sender: UIButton) { } override func viewDidLoad() { super.viewDidLoad() }

的代码
rootViewController?.present(navigationController, animated: true, completion: nil)

问题是,当我添加一个人,并返回主ViewController时,该表将不会重新加载。但是,当我关闭应用程序并再次打开时,数据将被提取并重新加载。

1 个答案:

答案 0 :(得分:0)

试试这个。将获取请求放在viewWillAppear中,并将其从viewDidLoad中删除。告诉我它是否有效。

 override func viewWillAppear(_ animated: Bool) {
        let fetchReq: NSFetchRequest<Person> = Person.fetchRequest()

        do{
            let people = try PersistenceService.context.fetch(fetchReq)
            self.people = people
            self.patientView.reloadData()
        }catch{

        }
         patientView.reloadData()
    }