无法保存到Core Data

时间:2015-11-05 06:30:11

标签: ios mysql swift core-data

我在我的应用中点按了一个保存按钮时运行了以下代码

let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext!
    print("checkpoint 1")
    let newJob = NSEntityDescription.insertNewObjectForEntityForName("Job", inManagedObjectContext: context)
    print("checkpoint 2")
    newJob.setValue(jobTitleField.text, forKey: "title")
    newJob.setValue(phoneNumberField.text, forKey: "phoneNumber")
    print("checkpoint 3")
    newJob.setValue(Double(hourlyRateField.text!), forKey: "hourlyRate")
    newJob.setValue(Double(doublePayField.text!), forKey: "doublePayRate")

    print("checkpoint 4")
    do {
        try context.save()
    } catch {
        print("There was error saving data.")
    }
    print("checkpoint 5")

    self.dismissViewControllerAnimated(true, completion: {})

但是,当我运行应用程序并通过 SQLiteManager 访问mysql数据库时,数据不会出现在数据库中。

任何人都可以看到我做错了什么或者我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

除了最新Swift的语法更改之外,您的代码看起来很好。如果您想尝试,以下保存方法适用于Swift 2.1

PS,用presentViewController.dismiss替换self.dismiss或者只是解散,因为self.dismiss将尝试删除当前vc的子vc,但我可以看到你试图删除self。

private func save(text:String, entityName:String, key:String) {
    if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
        let managedContext = appDelegate.managedObjectContext
        if let newjob = NSEntityDescription.entityForName(entityName, inManagedObjectContext: managedContext) {
            let job = NSManagedObject(entity: newjob, insertIntoManagedObjectContext: managedContext)
            job.setValue(text, forKey: key)

            //save
            do {
                try managedContext.save()
                //append it to your model in the project (most common to do)
            } catch (let error) {
                print("Not saved. \(error)")
            }
        }
    }
}