Search code examples
iosswiftxcodensmanagedobject

Swift - How can I save input data into Core Data?


I am trying to store user input to my core data but i am getting an error:

My code:

import UIKit
import CoreData

class AddFriendViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

    @IBOutlet weak var fName: UITextField!
    @IBOutlet weak var lName: UITextField!
    @IBOutlet weak var mobile: UITextField!
    @IBOutlet weak var gender: UIPickerView!
    @IBOutlet weak var address: UITextField!
    var pickerDataSource = ["Male", "Female"];
    var genderPick:String = "";

//getting picker data here

    @IBAction func addFriendBtn(sender: AnyObject) {
        let entityDescription = NSEntityDescription.entityForName("Friends", inManagedObjectContext: managedObjectContext)
        let friends = Friends(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)
        friends.firstName = fName.text!;
        friends.lastName = lName.text!;
        friends.mobile = mobile.text!;
        friends.gender = genderPick;
        friends.address = address.text!;

        var error: NSError?
        managedObjectContext!.save(&error) // error occurs here
        if let err = error {
            showMessage("Error While Adding to Core Data")
        } else {
            showMessage("Save to Core Data Successfully")
        }
    }

    func showMessage(msg: String)
        {
            let alert = UIAlertController(title: "Message", message: msg, preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
    }

}

Im getting an error in this line of code: managedObjectContext!.save(&error). The error is "cannot force unwrap value of non-optional type 'NSManagedObjectContext'"


Solution

  • var theError: NSError?
    do {
         try managedObjectContext!.save()
     } catch {
    
         theError = error 
         print("Unresolved error \(theError), \(theError.userInfo)")
    }
    

    According to Apple Doc, You need to add error handling code when you invoke save function.

    Handling Errors in Swift:

    In Swift, this method returns Void and is marked with the throws keyword to indicate that it throws an error in cases of failure.

    You call this method in a try expression and handle any errors in the catch clauses of a do statement, as described in Error Handling in The Swift Programming Language (Swift 3) and Error Handling in Using Swift with Cocoa and Objective-C (Swift 3).