Swift – NSTableView Sample Code

Using Xcode 6.0 Create a new cocoa project and select the language as Swift

Modify the MainMenu.xib by

Adding a NSTableView from the library

Set the AppDelegate as the delegate and datasource for the table view

add two columns in the tableview and name them as FirstName and LastName

State the identifier of the two columns to FirstName and LastName respectively. We will be using an Array of Dictionaries with keys as FirstName and LastName

Modify the AppDelegate.swift class by adding the below code

Note: For the below code to work, the table view needs to be cell based (not view based). Scroll down for the updated example that includes a column containing checkboxes as well. That is the working code.

22 comments on “Swift NSTableView sample code”

This tutorial is great, thanks a lot!
I edited the code to have a button that adds an entry to the existing array.
The button works and if I println the array after pushing the button, the array has the new entry at the bottom, but I got stuck while trying to refresh the table view. What is the correct way to refresh the view any time the array is modified?
Thanks again.

The table view is UI and the array is the datasource. So once we have set the array as the datasource of the table view, one can simply add a row / object / Dictionary to the array and reload the table view. the new row will start reflecting.

[self.myTableView reloadData]; if the myTableView is declared as a property or [_myTableView reloadData] should do the work]

Your help is greatly appreciated, Debasis! Could you extend the example above to show a third column that includes a checkbox for each row? I am unable to control the state of the checkbox from my AppDelegate. I am using an Array Controller to display the contents of an array in AppDelegate in the NSTableView.