swift - 文本更改时将文本视图保存到 CoreData
问题描述
我正在为 macOS 构建一个笔记应用程序,并且在用户编辑NSTextView
. 我使用textDidChange
函数来检测中的任何更改,NSTextView
然后将更改保存到 Core Data。但是,我的代码只会保存用户所做的第一次编辑,例如,如果我输入hello
,NSTextView
它只会保存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")
}
}
}
解决方案
推荐阅读
- xslt - 使用 DocBook/XLST-FO 生成带有章节编号的页面引文
- r - 如何将原子向量转换为可以在 R 中使用“$”符号的递归向量?
- sql - Oracle SQL 将多行聚合为单行
- java - 简单地调用 parallelStream 是否并行运行任务?
- java - 可选的
映射函数返回空 - php - 当商店用户在 Sylius 进行电子邮件确认时如何收听事件?
- python - Python - 从外部函数更新窗口类中的标签文本
- javascript - 无法在“窗口”GoogleTagManager 上执行“postMessage”
- php - 通过一个 PHP 页面发送两封单独的电子邮件,
- javascript - 如何根据其值更改 html 输出的颜色?