如何使用核心数据将此代码更改为swift 2?

时间:2015-12-04 00:41:38

标签: ios swift

我试图跟随这个例子,但我意识到它不是迅速的2.我是swift的新手所以我不知道如何将它改变为不同的东西。有人可以帮忙吗?

import UIKit
import CoreData

class ViewController: UIViewController {

    @IBOutlet weak var firstName: UITextField!
    @IBOutlet weak var lastName: UITextField!
    @IBOutlet weak var timeLabel: UITextField!
    @IBOutlet weak var costLabel: UITextField!
    @IBOutlet weak var commentLabel: UITextField!

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

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

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

    @IBAction func saveClient(sender: AnyObject) {
        let personDescription = NSEntityDescription.entityForName("Person", inManagedObjectContext: maContext)
    }

    // let person = Person(entity: personDescription!, insertIntoManagedObjectContext: maContext)

    person.fName = firstName.text
    person.lName = lastName.text
    person.time = timeLabel.int
    person.cost = costLabel.int
    person.comments = commentLabel.text

    var error:NSError?

    maContext?.save(&error)

    if let err = error
    {
        let a  = UIAlertView(title: "Error", message: err.localizedFailureReason, delegate: nil, cancelButtonTitle: "OK")
        a.show()
    }
    else{
        let a = UIAlertView(title: "Success", message: "Your Record is saved" , delegate: nil, cancelButtonTitle: "OK")

        a.show()
    }
}

2 个答案:

答案 0 :(得分:1)

抱歉,我没有足够的声誉发表评论,所以我会尽力回答你的问题。

代码似乎符合Swift 2标准。我不认为CoreData API已经升级,以利用新的do / try / catch语法进行错误处理,因此&error的保存中的NSManagedObjectContext似乎是细

答案 1 :(得分:0)

假设您的代码正确应该是这样的:

做{

    try maContext.save()
    let a = UIAlertView(title: "Success", message: "Your Record is saved" , delegate: nil, cancelButtonTitle: "OK")
    a.show()
} catch let error as NSError {
    let a  = UIAlertView(title: "Error", message: err.localizedFailureReason, delegate: nil, cancelButtonTitle: "OK")
    a.show()
}

代替您的代码:

var error:NSError?

    maContext?.save(&error)

    if let err = error
    {
        let a  = UIAlertView(title: "Error", message: err.localizedFailureReason, delegate: nil, cancelButtonTitle: "OK")
        a.show()
    }
    else{
        let a = UIAlertView(title: "Success", message: "Your Record is saved" , delegate: nil, cancelButtonTitle: "OK")

        a.show()
    }