Search code examples
swiftmacosswift4nstableview

Illegal NSTableView data source in swift 4


I can find no answers or solutions to a problem such as this for swift 4. I am writing for OSX and when I reload the data in my tableView with tableView.reloadData(), the terminal returns the error -

Illegal NSTableView data source (). Must implement numberOfRowsInTableView: and tableView:objectValueForTableColumn:row:

To my knowledge I have implemented numberOfRowsInTableView and tableView in the extension.

Can someone point me in the right direction?

    import Cocoa

    class ViewController2: NSViewController {


    var data: [[String: String]]?

    @IBOutlet weak var tableView: NSTableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        data = [
                [
                    "type" : "type1",
                    "details"  : "etc",
                    "cost" : "22"
                ],
                [
                    "type" : "type2",
                    "details"  : "etc",
                    "cost" : "33"
                ],
                [
                    "type" : "type3",
                    "details"  : "etc",
                    "cost" : "44"
            ]
        ]

        self.tableView.reloadData()
    }


    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

extension ViewController2: NSTableViewDataSource, NSTableViewDelegate{

    func numberOfRowsInTableView(tableView: NSTableView) -> Int {
        return (data?.count)!
    }

    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        let item = (data!)[row]
        let cell = tableView.makeView(withIdentifier: (tableColumn!.identifier), owner: self) as? NSTableCellView
        cell?.textField?.stringValue = item[(tableColumn?.identifier.rawValue)!]!
        return cell
    }
}

Solution

  • You are not using the Swift 4 API for the NSTableViewDataSource method. Instead of

    func numberOfRowsInTableView(tableView: NSTableView) -> Int {}
    

    Use these correct APIs:

    func numberOfRows(in tableView: NSTableView) -> Int
    

    See the official documentation for the data source API: https://developer.apple.com/documentation/appkit/nstableviewdatasource