【问题标题】:Error with NSTreeController - this class is not key value coding-compliant for the keyNSTreeController 出错 - 此类与键的键值编码不兼容
【发布时间】:2017-11-10 01:16:14
【问题描述】:

我是 Swift 新手,正在尝试学习如何使用 NSOutlineView 实现 NSTreeController。我一直在关注几个显示此类示例的指南,但我不断收到错误消息。我一步一步地跟着和/或尝试运行他们的源代码(如果有的话),但我得到了同样的错误。我开始认为 Swift 4 有一些变化,这使得这些 Swift 3 示例产生错误。由于在 Swift 4 中完成的示例并不多,我决定在这里提出问题来尝试一下。

我得到的错误是:

对于键 isLeaf,此类不符合键值编码。

我认为错误来自为 NSTreeController 设置的关键路径:

但是我不确定需要做什么来修复错误。

我有一个名为 Year 的简单模型类。

class Year: NSObject {

    var name: String

    init(name: String) {
        self.name = name
    }

    func isLeaf() -> Bool {
        return true
    }
}

我的视图控制器看起来像这样。

class ViewController: NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate {

    @IBOutlet weak var outlineView: NSOutlineView!
    @IBOutlet var treeController: NSTreeController!

    override func viewDidLoad() {
        super.viewDidLoad()

        addData()
        outlineView.delegate = self
        outlineView.dataSource = self
        }

    func addData() {
        let root = ["name": "Year", "isLeaf": false] as [String : Any]
    
        let dict: NSMutableDictionary = NSMutableDictionary(dictionary: root)
        dict.setObject([Year(name: "1999"), Year(name: "2000")], forKey: "children" as NSCopying)
        treeController.addObject(dict)
    }

    func isHeader(item: Any) -> Bool {
        if let item = item as? NSTreeNode {
            return !(item.representedObject is Year)
        } else {
             return !(item is Year)
        }
    }

    func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
        if isHeader(item: item) {
            return outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "HeaderCell"), owner: self)!
        } else {
            return outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "DataCell"), owner: self)!
        }
    }
}

当我运行程序时,它不会导致任何问题,但是当我展开节点以显示根的两个子节点时,它给出了我上面提到的错误。

【问题讨论】:

    标签: cocoa swift4 nsoutlineview nstreecontroller


    【解决方案1】:

    因为isLeafNSOutlineView在KVO中使用的,所以必须在isLeaf函数前面加上@objc

    @objc func isLeaf() -> Bool {
        return true
    }
    

    【讨论】:

      【解决方案2】:

      您要绑定的类需要符合 KVO。

      所以,它需要是 NSObject 的子类。 并且 objc 运行时需要访问。

      一种方法:

      @objcMembers
      class FileSystemItem: NSObject {
      

      或者,您可以使用 @objc 注释每个字段/函数

      Full Example

      【讨论】:

      • 添加 @objcMembers 解决了 KVO 兼容问题。干杯!
      猜你喜欢
      • 1970-01-01
      • 2017-09-27
      • 2012-08-18
      • 2015-08-27
      • 2011-03-17
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多