I have a table view that shows contacts sorted by alphabetic ordering and divide it to sections.
i am using -
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[dataSource keyName] ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
then for contacts without name i am using # sign as their first letter so all of them will be grouped in one group.
everything is great. the only thing i want is to push the # section to the end of the table, as for now it shows in the beginning of it.
any ideas?
thanks in advance
shani
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With