我正在为 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 的默认笔记应用程序中。但如何才能释放呢?
最佳答案
保存数据有两个子任务:使用 TextView 的内容更新核心数据实体并保存核心数据上下文。
要更新核心数据实体的内容,请将函数添加到保存 TextView 内容的 AddEditNotes
类。
func saveTextViewContents() {
note.text = textView.text
// Add any other code you need to store the note.
}
当 TextView 结束编辑或文本更改时调用此函数。如果在文本更改时调用此函数,则核心数据实体将始终是最新的。您不必将数据传递给应用程序委托(delegate),因为应用程序委托(delegate)具有 Core Data 托管对象上下文。
要保存核心数据上下文,请将第二个函数添加到保存上下文的 AddEditNotes
类。
func save() {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.saveContext()
}
}
此函数假设您在创建项目时选择了“使用核心数据”复选框。如果您这样做了,应用程序委托(delegate)有一个 saveContext
函数来执行核心数据保存。
您现在可以将在 viewWillDisappear
中编写的代码替换为对两个函数的调用,以保存 TextView 内容并保存上下文。
要编写的最后一个代码是转到应用程序委托(delegate)文件并将以下代码行添加到 applicationDidEnterBackground
和 applicationWillTerminate
函数:
self.saveContext()
通过添加此代码,当有人退出您的应用程序时,您的数据将保存。
关于ios - 在 UITextView 中保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59595180/