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