2015-11-05 207 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)") 
      } 
     } 
    } 
}