Jakob Jakob - 1 year ago 144
Swift Question

Getting array objects into NSTableView

I want to catch information from an array and display it into my NSTableView. I'm unsure what I need to do for that (I am very new to Swift and programming in general).

My table view looks like this:

enter image description here

I want to get value name from my array and display it in the name table with the NSTableView. I've found this tutorial on Ray Wenderlich but the code is very outdated and I don't want to use old things within my project which might not work anymore in newer OS versions.

It seems that I need an

[NSTableViewDataSource numberOfRows][3]
and viewFor.

Any examples on how to do this - maybe someone made this a few weeks ago with Swift 3? :D

The information within the array will be generated by the following:

var devices = [Device]()
let quantityDevices = quantityData.intValue

for i in 0...quantityDevices-1 {

let newDevice = Device()
print("created new device")

newDevice.name = titleData.stringValue + "-\(i)"

print("now we have \(devices.count) devices in our array")


Answer Source

The important part of the code you need is the DataSource delegate functions:

extension ViewController : NSTableViewDataSource {
  func numberOfRows(in tableView: NSTableView) -> Int {
    return devices.count

  func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

    // 1 - get the device for this row
    guard let device = devices[row] else {
      return nil

    // 2 - configure the cell with the device data
    return nil

There is an example here on StackOverflow that should give a better example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download