我正在创建笔记应用程序,当我在编辑笔记内容后按“完成”按钮时,它不会更新内容,而是会创建一个新笔记并保留旧笔记而不更新。
我该如何解决这个问题
我知道问题出在哪里
这是代码
@IBAction func save(sender:UIBarButtonItem) {
let title = titleField.text
let text = textView.text
if (text.isEmpty){
let alertController = UIAlertController(title: "Warning !", message: "You need to write something first", preferredStyle: .Alert)
let okayAction = UIAlertAction(title: "OK", style: .Default) { (action) in
print(action)
}
alertController.addAction(okayAction)
self.presentViewController(alertController, animated: false) {
}
}else{
if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext {
note = NSEntityDescription.insertNewObjectForEntityForName("Note", inManagedObjectContext: managedObjectContext) as! NoteData
note.title = title!
note.text = text!
do {
try managedObjectContext.save()
} catch {
print(error)
return
}
}
self.navigationController?.popViewControllerAnimated(true)
}
}
最佳答案
您正在创建一个新笔记,因为您在保存函数中调用了 NSEntityDescription.insertNewObjectForEntityForName
。
您可以只保留对当前正在更新的注释的引用,更新其文本,然后保存。或者您可以使用 Find-Or-Create 模式。这将使您能够首先根据某些条件搜索现有笔记,如果找到符合条件的笔记,则返回它或创建符合条件的新笔记。虽然,只保留对您当前正在处理的笔记的引用是一个更好的选择。
关于ios - 如何使用核心数据框架更新数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34472801/