Reputation: 143
I'm trying to implement a custom sort for a column in an NSTableView. The data for this column contains double values inside a custom object, where some of the values are positive, some are negative, and some are "not applicable" (i.e. this row doesn't matter and should be sorted to the bottom).
I've created a comparison method in my table view that looks like this...
- (NSComparisonResult) myCompare:(id) obj1 : (id) obj2 {
if (obj1 < obj2)
return NSOrderedAscending;
else if (obj1 > obj2)
return NSOrderedDescending;
else
return NSOrderedSame; // they must be the same
};
...where the comparisons of obj1 and obj2 actually dig into the data of the objects being compared.
In my storyboard, the Sort key for the column is: myObject
And the selector for the column is: myCompare:
Running the code and clicking on the column I wish to sort on results in:
Thread 1: "-[__NSCFNumber myCompare:]: unrecognized selector sent to instance 0x600003824740"
Obviously, things aren't set up quite right. I made some changes to my viewWillAppear method to set the sort descriptors, but the same error appears. How do I get my table view to recognize and call the custom sort routine?
Upvotes: 0
Views: 28
Reputation: 143
I figured out what the problem was, which had to do with my custom comparison method, as opposed to anything I was doing in the storyboard or setting up the sort descriptors. Apple's Table View Programming Guide goes into some detail about the comparison selector stating, "This comparison selector expects a single parameter" (Table View Programming Guide for Mac), where I had been expecting a method that takes a pair of parameters like sorting an NSArray. The correct custom comparison method goes in the custom object that will be compared and looks like this:
- (NSComparisonResult) myCompare:(id) obj {
myObject *objToCompare = (myObject *) obj;
if (objToCompare.value < value)
return NSOrderedAscending;
else if (objToCompare.value > value)
return NSOrderedDescending;
else
return NSOrderedSame; // they must be the same
};
Upvotes: 0