首页 > 解决方案 > 文本更改时将文本视图保存到 CoreData

问题描述

我正在为 macOS 构建一个笔记应用程序,并且在用户编辑NSTextView. 我使用textDidChange函数来检测中的任何更改,NSTextView然后将更改保存到 Core Data。但是,我的代码只会保存用户所做的第一次编辑,例如,如果我输入helloNSTextView它只会保存h而不是hello. 我想知道如何解决它?谢谢您的帮助。

这是代码:

class ViewController: NSViewController, NSTextViewDelegate, NSTableViewDataSource, NSTableViewDelegate {

    @IBOutlet var textArea: NSTextView!
    @IBOutlet weak var noteList: NSTableView!
    
    
    
    let context = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    var notes = [Testnote]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        loadData()        
        textArea.textStorage?.setAttributedString(notes[0].noteItem!)
        
        textArea.delegate = self
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
    
    // MARK: - Tableview stuff
    
    func numberOfRows(in tableView: NSTableView) -> Int {
        return notes.count
    }

    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "rowNo"), owner: self) as? NSTableCellView {
            cell.textField?.stringValue = "sth here"
            return cell

        }
        return nil
    }
    
    func tableViewSelectionDidChange(_ notification: Notification) {
        if noteList.selectedRow >= 0 {
            let selectedNote = notes[noteList.selectedRow]
            textArea.textStorage?.setAttributedString(selectedNote.noteItem!)
        }
    }
    
    
    func textDidChange(_ notification: Notification) {
        if let textview = notification.object as? NSTextView {
            notes[0].noteItem = textview.attributedString()
            saveData()
        }
        
    }
    
        
    func loadData() {
        let request: NSFetchRequest<Testnote> = Testnote.fetchRequest()
        do {
            notes = try context.fetch(request)
        } catch {
            print("sth wrong")
        }
    }
    
    func saveData() {
        do {
            try context.save()
        } catch {
            print("Error saving \(error)")
        }
    }
    
    
    
    @IBAction func addButton(_ sender: Any) {
        // Create new NSObject and assign values
        let newnote = Testnote(context: context)
        newnote.noteItem = textArea.attributedString()
        (NSApplication.shared.delegate as? AppDelegate)?.saveAction(nil)
        
    }
    
    
    @IBAction func delete(_ sender: NSButton) {
        context.delete(notes[noteList.selectedRow])
        do {
            try context.save()
        } catch {
            print("Error")
        }
    }
}

标签: swiftmacos

解决方案


推荐阅读