How to remove optional for coreData

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

@timswift Thanks very much for your question!

First off, I would suggest that you not access your ManagedObjectContext (MOC) via the AppDelegate. Rather, what you should do is use Dependency Injection, and create a MOC property on your VC class, to which you assign the MOC object inside the AppDelegate method: “didFinishLaunchingWithOptions”. In doing so, you have a local MOC property that you can use inside your class, which means you eliminate the code:

            guard let appDelage = UIApplication.shared.delegate as? AppDelegate else {
                return
            }
            let managedContext = appDelage.persistentContainer.viewContext

which you use in two places.

Having said that, I am not sure what you’re doing with this line of code:

lxe.text = String(describing: people.description)

“people” is an array of NSManagedObject subclasses, so what you need to do is obtain an object from the array in order to provide the text for the label. You’re not doing this. I think this is your problem.

I hope this helps!

All the best!

This topic was automatically closed after 166 days. New replies are no longer allowed.