Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data (SQLite backed) custom sorting of strings

I currently have a SQLite backed Core Data app where I am fetching records sorted on firstName and then lastName.

The issue is that I have some names like (John Doe) and they are coming back at the top of the list, it seems the default sorting behavior is done in ASCII sort order.

Is there anyway to force these records to show up after Z?

I have read about custom sort descriptors but they do not seem to work because Core Data falls back on SQLite for sorting.

Update

Here is a sample list of what my data looks like now

(Abe Simpson)
(Bob Dole)
(Chris Rock)
Alan West
Brian Regan

What I want it to look like

Alan West
Brian Regan
(Abe Simpson)
(Bob Dole)
(Chris Rock)
like image 552
Chris Wagner Avatar asked Mar 25 '26 07:03

Chris Wagner


2 Answers

Add a new BOOL attribute called parenthesized, then...

- (void)setName:(NSString *)name
{
    [self willChangeValueForKey:@"name"];
    [self setPrimitiveName:name];
    [self didChangeValueForKey:@"name"];
    self.parenthesized = ([name hasPrefix:@"("] &&
                          [name hasSuffix:@")"]);
}

And when you do the fetch:

[fetchRequest setSortDescriptors:
 [NSArray arrayWithObjects:
  [NSSortDescriptor sortDescriptorWithKey:@"parenthesized" ascending:NO],
  [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES],
  nil]];
like image 124
Daniel Dickison Avatar answered Mar 28 '26 03:03

Daniel Dickison


What is the reason for the parenthesis ? You could probably make things easier for yourself if you replaced this implicit information with explicit information in a separate property that can then be used to direct sorting

like image 33
Harald Scheirich Avatar answered Mar 28 '26 01:03

Harald Scheirich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!