[英]How can I reload the tableview from another viewController when I add a new value?
I already tried the answers here at StackOverFlow with the same question as mine, but it didn't work. 我已经在StackOverFlow尝试了与我相同的问题,但没有成功。
Here is my story board. 这是我的故事板。
Here is the code for my ViewController
这是我的
ViewController
的代码
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()
}
and here is the code of my TableViewController
这是我的
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()
}
The problem is that when I add a person, and go back to the main ViewController, the table won't reload. 问题是,当我添加一个人并返回到主ViewController时,该表将不会重新加载。 However, when I close the app and open again the data will be fetch and reloaded.
但是,当我关闭应用程序并再次打开时,数据将被提取并重新加载。
Try this. 尝试这个。 Put the fetch request in the viewWillAppear and remove it from the viewDidLoad.
将获取请求放入viewWillAppear中,并将其从viewDidLoad中删除。 Tell me if it works.
告诉我是否可行。
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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.