我已经在StackOverFlow上尝试了与我相同的问题,但它没有用。
这是我的故事板。
以下是我的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时,该表将不会重新加载。但是,当我关闭应用程序并再次打开时,数据将被提取并重新加载。
答案 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()
}