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

时间:2016-10-07 02:04:35

标签: ios swift xcode nsmanagedobject

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

我的代码:

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)。错误是“无法强制解包非可选类型的值'NSManagedObjectContext'”

1 个答案:

答案 0 :(得分:0)

val student = getStudentRollNo(name)
val detailsFuture = student map {s => getRank(rollNo) }
val rankFuture = student map {s => getDetails(rollNo) }

for {
  rank <- rankFuture
  details <- detailsFuture
} yield (rank + details)

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

  

处理Swift中的错误:

     

在Swift中,此方法返回Void并标记为throws   表示在失败的情况下抛出错误的关键字。

     

您可以在try表达式中调用此方法并处理其中的任何错误   捕获do语句的子句,如The中的错误处理中所述   Swift编程语言(Swift 3)和使用Swift时的错误处理   与Cocoa和Objective-C(Swift 3)。