我正在为iOS编写便笺应用程序,我希望用户在自动键入时自动保存用户在便笺中输入的所有数据。我正在使用Core Data,现在我将数据保存在viewWillDisappear上,但是我希望如果用户终止该应用程序,或者该应用程序将在后台自动终止,则也要保存数据。
我使用此代码:
import UIKit
import CoreData
class AddEditNotes: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
var note: Note!
var notebook: Notebook?
var userIsEditing = true
var context: NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
context = appDelegate.persistentContainer.viewContext
if (userIsEditing == true) {
textView.text = note.text!
title = "Edit Note"
}
else {
textView.text = ""
}
}
override func viewWillDisappear(_ animated: Bool) {
if (userIsEditing == true) {
note.text = textView.text!
}
else {
self.note = Note(context: context)
note.setValue(Date(), forKey: "dateAdded")
note.text = textView.text!
note.notebook = self.notebook
}
do {
try context.save()
print("Note Saved!")
}
catch {
print("Error saving note in Edit Note screen")
}
}
}
我知道我可以为此使用applicationWillTerminate,但是如何将用户输入的数据传递到那里? Apple的默认Notes应用程序中有此功能。但是如何发布?
保存数据有两个子任务:使用文本视图的内容更新Core Data实体并保存Core Data上下文。
要更新Core Data实体的内容,请向AddEditNotes
类中添加一个用于保存文本视图内容的函数。
func saveTextViewContents() {
note.text = textView.text
// Add any other code you need to store the note.
}
当文本视图结束编辑或文本更改时调用此函数。如果在文本更改时调用此函数,则核心数据实体将始终是最新的。您不必将数据传递给应用程序委托,因为该应用程序委托具有Core Data托管对象上下文。
要保存Core Data上下文,请向AddEditNotes
类添加第二个函数来保存上下文。
func save() {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.saveContext()
}
}
此功能假定您在创建项目时选择了使用核心数据复选框。如果您这样做了,则应用程序委托具有saveContext
函数,该函数执行Core Data保存。
您现在可以用对两个函数的调用替换在viewWillDisappear
中编写的代码,以保存文本视图内容和上下文。
最后编写的代码是转到您的应用程序委托文件,并将以下代码行添加到applicationDidEnterBackground
和applicationWillTerminate
函数中:
self.saveContext()
通过添加此代码,当有人退出您的应用程序时,您的数据将保存。