-2

The following does not work. Here is what it tells me after the app crashes:

fatal error: unexpectedly found nil while unwrapping an Optional value
class TeacherInputViewController: UIViewController {

    @IBOutlet var textName: UITextField!
    @IBOutlet var textEmail: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func btnSave(sender: AnyObject) {

        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let entity = NSEntityDescription.entityForName("Teachers", inManagedObjectContext: context)          
        let newTeacher = TeacherObject(entity: entity!, insertIntoManagedObjectContext: context)

        newTeacher.name = textName.text
        newTeacher.email = textEmail.text

        context.save(nil)

        println(newTeacher)
        self.navigationController?.popToRootViewControllerAnimated(true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Why am I getting an error unwrapping an optional values?

EDIT: this is the line it says is causing the problem: let newTeacher = TeacherObject(entity: entity!, insertIntoManagedObjectContext: context)

Henry OM
  • 83
  • 7
  • It should indicate which line it's encountering that error on. That would be useful information for us to know. – Mike S Sep 14 '14 at 15:35
  • possible duplicate of [fatal error: unexpectedly found nil while unwrapping an Optional value in Swift](http://stackoverflow.com/questions/24715343/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-value-in-swift) – jww Sep 14 '14 at 15:41
  • context. save = (nil) ??? Ur saving nil – Abdullah Ossama Omari Sep 14 '14 at 17:40

1 Answers1

0

The unwrapped object must be entity! because it is the only unwrapped object in the function call. Your call to create the variable entity thus most likely returns nil.

  1. Either you misspelled the entity name "Teachers" (looks fishy: why is it plural?),
  2. or your managed object context is nil, in which case you have to go back to the app delegate and check why that is the case.
Mundi
  • 79,884
  • 17
  • 117
  • 140