Swift - 如何将输入数据保存到 Core Data 中?

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

我正在尝试将用户输入存储到我的核心数据中,但出现错误:

我的代码:

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

}

我在这行代码中遇到错误:managedObjectContext!.save(&error)。错误是"cannot force unwrap value of non-optional type 'NSManagedObjectContext'"

var theError: NSError?
do {
     try managedObjectContext!.save()
 } catch {

     theError = error 
     print("Unresolved error \(theError), \(theError.userInfo)")
}

根据 Apple Doc,您需要在调用保存功能时添加错误处理代码。

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).