Reputation: 31955
I use view-based NSTableView
in my Cocoa app which is written in Swift, and want to implement a sort functionality on two table columns. However, in Objective-C, you can implement it by first setting the "Sort Key" in Attribute Inspector, and then implement the data source delegate method named tableView: sortDescriptorsDidChange:
.
However, this method takes sortDescriptor
as a parameter and lets developers use it within the method, like so:
- (void) tableView:( NSTableView *) tableView sortDescriptorsDidChange:( NSArray *) oldDescriptors {
[self.songs sortUsingDescriptors:tableView.sortDescriptors];
[tableView reloadData];
}
However, in Swift Array, there are no such method as sortUsingDescriptors
. So I first tried to convert Array
to NSMutableArray
in order to use the NSMutableArray
's method, but since my Swift Array is defined as AnyObject[]
, it cannot be casted to NSMutableArray
.
So how should I implement the sort functionality to the table view in Swift? I know Swift Array can use sort
function to sort the object by comparing the two arguments and returning bool values, but is it possible to use sortDescriptors
to sort the table? Or should I just ignore the sortDescriptors
argument and instead write my own sort logic manually? (but then I don't know how to tell what column is clicked without the sortDescriptors
value).
Upvotes: 2
Views: 4518
Reputation: 31955
Probably the best way, at least right now, is to first convert it to NSMutableArray
and then sort it using NSMutableArray
's sortUsingDescriptors
method, and finally convert it back to the original Array, like so:
func tableView(tableView: NSTableView!, sortDescriptorsDidChange oldDescriptors: [AnyObject]) {
var songsAsMutableArray = NSMutableArray(array: songs)
songsAsNSMutableArray.sortUsingDescriptors(tableView.sortDescriptors)
songs = songsAsNSMutableArray
tableView.reloadData()
}
By the way, var songsAsMutableArray = songs as NSMutableArray
causes an error: NSArray is not a subtype of NSMutableArray
, so I created an NSMutableArray
instance as shown above.
Upvotes: 2