I am trying to fetch core data and place it on a label. I am trying to do that in function saveData. You can see all of the optional data before the entity in the photo below.
I don’t know what this is even called but I want everything but the entity to be removed.
import UIKit;import CoreData
class ViewController: UIViewController {
@IBOutlet var lxe: UILabel!
@IBOutlet var rot: UITableView!
@IBOutlet var enterName: UITextField!
var people : [NSManagedObject] = []
@IBAction func iDontLikeSchool(_ sender: Any) {
if(enterName.text?.isEmpty)! {
} else {
saveData(name: enterName.text!)
showdata()
}}
func alertmsg(name:String){
let alert = UIAlertController(title: "Enter", message: "now", 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()
lxe.text = String(describing: people.description)
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 {
}
} catch let err as NSError {
print("judo", err)
}
rot.reloadData()
}}
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
}
}