Copy one or multiple NSTableView rows, Swift

So here’s a simple yet tricky one: you’ve created your NSTableView but now you would like to allow a user to copy to the clipboard one, or a couple of rows. How do you do it?

1. Implement the function copy (func copy(sender: AnyObject?){}), do not confuse with the method for duplicating an object

 2. Get the index set from the tableView selection and retrieve the relevant rows from your dataSource. From there is just a matter of composing the text to copy into the pasteboard. 

Here’s my code structure, implemented in my NSTableViewController:

func copy(sender: AnyObject?){

        

        var textToDisplayInPasteboard = “”

        let indexSet = tableView.selectedRowIndexes

        for (_, rowIndex) in indexSet.enumerate() {

            var iterator: CoreDataOjectType

            iterator=tableDataSource.objectAtIndex(rowIndex)

            textToDisplayInPasteboard = (iterator.name)! 

        }

        let pasteBoard = NSPasteboard.generalPasteboard()

        pasteBoard.clearContents()

        pasteBoard.setString(textToDisplayInPasteboard, forType:NSPasteboardTypeString)

        

    }

This will also automatically enable the Edit -> Copy (Command + C) menu, that would be disabled -grayed out- without this code. 

Questions / comments? I’m at @MarcMasVi 

Marc