The best way to do this is to create your own custom sort descriptor using the sortDescriptorWithKey:ascending:comparator: method. This lets you create your own comparison function, which you specify using a block.
First, create a comparison function. If you've never programmed with blocks before, now is the time to learn!
NSComparisonResult (^myStringComparison)(id obj1, id obj2) = ^NSComparisonResult(id obj1, id obj2) {
// Get the first character of the strings you're comparing
char obj1FirstChar = [obj1 characterAtIndex:0];
char obj2FirstChar = [obj2 characterAtIndex:0];
// Check if one (but not both) strings starts with a '#', and if so, make sure that one is sorted below the other
if (obj1FirstChar == '#' && obj2FirstChar != '#') {
return NSOrderedDescending;
} else if (obj2FirstChar == '#' && obj1FirstChar != '#') {
return NSOrderedAscending;
}
// Otherwise return the default sorting order
else {
return [obj1 compare:obj2 options:0];
}
};
Now that you have your comparison function, you can use it to create a sort descriptor:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:[dataSource keyName] ascending:YES comparator:myStringComparison];
You can now use that sort descriptor just like you would any other, and your list will have the # items sorted to the end!
NSComparisonResult (^myStringComparison)(id obj1, id obj2) = ^NSComparisonResult(id obj1, id obj2) { ... };
? I understand how it works, but what language construct is it? Is it just a function? – Rossiter