2015-11-05 171 views
0

我有一个运行时我在我的应用程序点击保存按钮无法保存到核心数据

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

然而,当我运行应用程序,并通过访问MySQL数据库的SQLiteManager下面的代码中,数据不会出现在数据库中。

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

回答

0

你的代码看起来很好,除了对最新的Swift进行一些语法修改。下面的保存方法适用于Swift 2.1,如果你想尝试它

PS,用presentsViewController.dismiss替换self.dismiss,或者关闭self.dismiss将尝试删除当前vc的子vc,但我可以看到你正试图消除自我。

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