需要帮助才能使保存功能正常工作,我是CoreData的新手,我只是跟随树屋课程,但树屋课程使用的是以前版本的xcode或不同版本的swift,因为当我跟着它时它给了我错了。
错误表示"类型'项目'的值没有会员'文字'"
class popUpViewController: UIViewController {
let managedObjectContext = CoreDataStack().managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet var keyField: UITextField!
@IBAction func save(_ sender: Any) {
guard let text = keyField.text, !text.isEmpty else { return }
let item = NSEntityDescription.insertNewObject(forEntityName: "Item", into: managedObjectContext) as! Item
item.text = text
}
}
答案 0 :(得分:0)
尝试这样的事情,让我知道它是否有效:
func setValuesToModel(){
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Item", in: context)
let item = NSManagedObject(entity: entity!, insertInto: context)
item.setValue("text You want", forKeyPath: "text")
do {
try context.save()
} catch {
print("Could not save. \(error) , \(error.localizedDescription)")
}
}
答案 1 :(得分:0)
您可以创建如下所示的func,只需传递要存储的文本即可。根据您的要求更新密钥和实体名称
func save(text: String) {
// 1 fetching item and updating with text
let item = NSEntityDescription.entity(forEntityName: "Item", in: managedObjectContext)!
item.text = text // if you have created model class use this or user below line
// item.setValue("Sample Text", forKeyPath: "text") //key will be the attribute name you have created
// 2 saving part
do {
//save tour context after setting value
try managedObjectContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}