gpt4 book ai didi

ios - 无法保存到核心数据

转载 作者:行者123 更新时间:2023-11-29 21:52:09 27 4
gpt4 key购买 nike

当我点击应用程序中的保存按钮时,我会运行以下代码

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数据库时,数据不会出现在数据库中。

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

最佳答案

除了针对最新 Swift 的一些语法更改之外,您的代码看起来不错。如果你想尝试一下,下面的保存方法在 Swift 2.1 上效果很好

PS,用presentingViewController.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)")
}
}
}
}

关于ios - 无法保存到核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33537996/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com