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

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

}

我在这行代码中收到错误:managementObjectContext!.save(&error)。错误是“无法强制解开非可选类型‘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).

关于ios - Swift - 如何将输入数据保存到 Core Data 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39908249/

相关文章:

ios - 简单动画问题 Xcode 7 Swift

objective-c - 如果我的服务器出现故障无法提供内容,如何取消应用内购买? (iOS)

ios - 实例化 View ,然后导航离开

iphone - 如何为特定文件添加 ARC?

ios - Afnetworking post 请求的代码提取

ios - 哪些权利是特殊权利?它们是如何工作的?

ios - iPad 方向的响应式设计模板

ios - 在 iOS Swift 中解析 JSON 格式的最佳方法是什么?

ios - UIColor 不适用于 RGBA 值

ios - 如何在操作表中进行多项选择和部分?