首页 > 解决方案 > 在 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 的默认笔记应用程序中。但它怎么能被释放呢?

标签: iosswiftcore-datauitextviewsaving-data

解决方案


保存数据有两个子任务:使用文本视图的内容更新 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为对两个函数的调用,以保存文本视图内容并保存上下文。

最后要编写的代码是转到您的应用程序委托文件并将以下代码行添加到applicationDidEnterBackgroundandapplicationWillTerminate函数中:

self.saveContext()

通过添加此代码,您的数据将在有人退出您的应用程序时保存。


推荐阅读