简体   繁体   中英

How to sort NSTableView in Swift using sortDescriptors?

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM