NSArrayController 排序:"this class is not key value coding-compliant for the key"

NSArrayController sorting: "this class is not key value coding-compliant for the key"

我正在尝试在 NSTableView 中设置排序。 NSArrayController 绑定到一个数组:dynamic var dataArray = [Person]()。 填充 tableView 到目前为止工作正常,但在排序时我陷入了这个错误。 我的设置是:

1: 在 IB: ArrayController, Binding Inspector:

   - Sort Descriptors bind to ViewController
   - Model Key Path: self.customSortDescriptors

2: 在 IB: tableView, Binding Inspector:

(这里我收到错误:"this class is not key value coding-compliant for the key customSortDescriptors.")

   - Sort Descriptors bind to ArrayController
   - Controller Key: arrangedObjects
   - Model KEy Path: customSortDescriptors

3:在 IB 中:列 "Name",属性检查器:

   - Sort Key: name
   - Selector: caseInsensitiveCompare:

在ViewController中:

class ViewController: NSViewController {

    @IBOutlet var arrayController: NSArrayController!

    @IBOutlet var tableView: NSTableView!

    dynamic var dataArray = [Person]()

    dynamic var customSortDescriptors = [NSSortDescriptor(key: "name", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))];

    override func viewDidLoad() {
        super.viewDidLoad()

        dataArray.append(Person(name: "Noah", familyName: "Vale", age: 72))
        dataArray.append(Person(name: "Sarah", familyName: "Yayvo", age: 29))
        dataArray.append(Person(name: "Shanda", familyName: "Lear", age: 45))

    }

}

一切正常,直到我从上面设置第二步:2: in IB: tableView, Binding Inspector:然后我收到错误:this class is not key value coding-compliant for the key customSortDescriptors.

人 class:

class Person : NSObject {
    var name:String
    var familyName:String
    var age = 0

    override init() {
        name = "name"
        familyName = "family"
        super.init()
    }

    init(name:String, familyName:String, age:Int) {
        self.name = name
        self.familyName = familyName
        self.age = age
        super.init()
    }
}

这是一个演示项目:https://drive.google.com/file/d/0BwRghT926ZpyMVhZMHJqTGFOS3c/view

错误发生是因为阵列控制器没有 属性 customSortDescriptors

tableView.sortDescriptors 绑定到 arraycontroller.sortDescriptors (controllerKey!)。


但是,如果您想通过单击 header 启用列排序,请在 table 列中添加 Sort KeySelector 的值:

在这种情况下,您只需要从 table 视图到数组控制器的绑定,如第一张图片所示。