2

In Swift 4, when I try to sort a column by clicking its header, nothing happens :

tableView

Here's my code:

import Cocoa

class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
var persons = [Person(name: "John", age: "30"), Person(name: "Mike", age: "25"), Person(name: "Mary", age: "28")]

@IBOutlet weak var tableView: NSTableView!

override func viewDidLoad() {
    super.viewDidLoad()

}

func numberOfRows(in tableView: NSTableView) -> Int {
    return persons.count
}

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
    if tableColumn == tableView.tableColumns[0] {
        let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "nameCellView"), owner: nil) as? NSTableCellView
    cell?.textField?.stringValue = persons[row].name
        return cell
    }
    if tableColumn == tableView.tableColumns[1] {
        let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "ageCellView"), owner: nil) as? NSTableCellView
        cell?.textField?.stringValue = persons[row].age
        return cell
    }
    return nil
}

// I think I have to change something here
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
    let personsAsMutableArray = NSMutableArray(array: persons)
    personsAsMutableArray.sort(using: tableView.sortDescriptors)
    persons = personsAsMutableArray as! [Person]
    tableView.reloadData()
}
}

import Cocoa

class Person: NSObject {

var name: String
var age: String

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

tableColumAttributes tableColumnAttributes2

When I run, I have this message: Unknown Window class (null) in Interface Builder file, creating generic Window instead". When I sort a column by clicking its header, I have this message concerning the Person class: this class is not key value coding-compliant for the key name.

I think the 2016 comments of this question (from which part of this code is copied) could help.

EDIT: The solution is to add @objcMembers to the Person class (see the comments below).

Thank you.

Tommy V.
  • 67
  • 7
  • 2
    [Swift 4 “This class is not key value coding compliant”](https://stackoverflow.com/questions/44762460/swift-4-this-class-is-not-key-value-coding-compliant) – Willeke Sep 29 '17 at 12:50
  • Thank you! I added `@objcMembers`to the `Person` class. – Tommy V. Sep 29 '17 at 13:04

0 Answers0