简体   繁体   中英

Cannot save to Core Data

I have the following code that runs when I tap a save button in my app

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

However, when I run the app, and access the mysql database through SQLiteManager , the data does not appear in the database.

Can anyone see what I'm doing wrong or something that I've missed out?

Your code looks fine except with some syntax changes for the latest Swift. The following save method works fine for on Swift 2.1 if you wanna try it

PS, replace self.dismiss with presentingViewController.dismiss or just dismiss as self.dismiss will attempt to remove child vc of the current vc but I can see you're attempting to remove 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)")
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM