I’ve been attempting this for two days, and constantly running into dead ends.
I’ve been through Aaron Hillegass’s Cocoa Programming for MAC OS X, and done all the relevant exercises dealing with NSTableview and mutable arrays, and I have been attempting to modify them to suit my needs.
However none of them seem to be using an array with objects as a data source, it seems to use the tableview as the datasource.
I’m trying to implement Jonas Jongejan’s "reworking" of my code here, with a Cocoa front end to display the results.
Any pointers or suggestions I know this should be simple, but I’m lost in the wilderness here.
I can populate the table by setting the array
It’s pretty simple really, once you get to understand it (of course!). You can’t use an NSArray directly as a table source. You need to either create a custom object that implements NSTableViewDataSource or implement that protocol in some existing class – usually a controller. If you use Xcode to create a standard document based application, the document controller class – (it will be called MyDocument) is a good class to use.
You need to implement at least these two methods:
If you have a mutable array whose values you’d like to use in a table view with one column, something like the following should do as a start:
It has just occurred to me that you could add the above two methods as a category to NSArray replacing
myMutableArraywithselfand then you can use an array as a data source.Anyway, with a mutable array, it is important that any time you change it, you need to let the table view know it has been changed, so you need to send the table view
-reloadData.If your table view has more than one column and you want to populate it with properties of objects in your array, there’s a trick you can do to make it easier for yourself. Let’s say the objects in your array are instances of a class called Person with two methods defined:
and you want your table view to have a column for each of those, you can set the
identifierproperty of each column to the name of the property in Person that that column displays and use something like the following:If you replace
valueForKey:withvalueForKeyPath:and your Person class also has the following methods:you can add table columns with identifiers like:
father.fullNameormother.familyNameand the values will be automatically populated.