NSSortDescriptor - push # and numbers to the end of the list - iphone xcode
Asked Answered
M

1

7

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

Masterstroke answered 30/1, 2011 at 7:52 Comment(0)
H
7

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!

Homage answered 28/6, 2012 at 17:38 Comment(2)
What is 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
It's a block object, which is much like a regular function. You can read more about them in the Apple docs.Homage

© 2022 - 2024 — McMap. All rights reserved.