ios - 在 UITextView 中保存数据
问题描述
我正在为 iOS 编写笔记应用程序,我希望用户在笔记中输入的所有数据都会在用户自动输入时自动保存。我正在使用核心数据,现在我将数据保存在 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 的默认笔记应用程序中。但它怎么能被释放呢?
解决方案
保存数据有两个子任务:使用文本视图的内容更新 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 托管对象上下文。
要保存 Core Data 上下文,请向保存上下文的AddEditNotes
类添加第二个函数。
func save() {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.saveContext()
}
}
此功能假定您在创建项目时选择了 Use Core Data 复选框。如果你这样做了,应用程序委托有一个saveContext
执行核心数据保存的函数。
您现在可以将您编写的代码替换viewWillDisappear
为对两个函数的调用,以保存文本视图内容并保存上下文。
最后要编写的代码是转到您的应用程序委托文件并将以下代码行添加到applicationDidEnterBackground
andapplicationWillTerminate
函数中:
self.saveContext()
通过添加此代码,您的数据将在有人退出您的应用程序时保存。
推荐阅读
- arrays - 将字符串转换为反应组件
- c++ - 调用 onMessage 后 ActiveMQ 消费者内存使用量不断增加
- apache-kafka - 具有多个分区的消费者不会交错
- python - 调用类实例(类中的函数)上的方法,该方法调用该类中的其他函数
- php - Laravel 存储磁盘将文件从 sftp 保存到本地
- excel - 如何对包含#N/A 的范围求和,但如果该范围包含所有#N/A,则返回#N/A?
- python - 如何导入已经从父脚本导入的库?
- flutter - 当我在颤动中按下 RaisedButton 时,我想从 TextFormField 中获取值
- c - 如何在 ebpf 中使用 seccomp 过滤器?
- elasticsearch - 如何使用弹性数据源在 Grafana 中命名图形