开发者

Core Data (SQLite backed) custom sorting of strings

开发者 https://www.devze.com 2023-01-29 08:12 出处:网络
I currently have a SQLite backed Core Data app where I am fetching records sorted on firstName and then lastName.

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)
开发者_StackOverflow中文版(Chris Rock)


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]];


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


Read up on custom collations in SQLite. You probably do not have access to them on the i-devices though.


I think there is a really simple answer/solution. This works for me locally (not on an iPhone).

order by replace(firstName, '(','')

After reading back over your post, you wanted them to be at the bottom. The above would sort them as if the parenthesis were ignored. Below would get the output you wanted (although seems somewhat hackish).

order by replace(firstName, '(','ZZZ')


when you do the core data fetch, you get an array back, sort the array using the- (void)sortUsingSelector:(SEL)comparator method. you can then write your own sorting method which returns NSOrderAscending if the element is earlier, NSOrderDescending if it is later, and NSOrderSame if its the same.

0

精彩评论

暂无评论...
验证码 换一张
取 消