NSSortDescriptor cross out the prefix "the"

I have a group of artists stored in CoreData, and I want to sort them by name, but ignoring the prefix "the". So, for example, "The Beatles" will be sorted as "Beatles", sort of like iTunes / iPod.

So, I tried adding my own property cleanNameto my Artist model so that it could be used for sorting with:

NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"cleanName" ascending:YES];

This explicitly leads to the application, since cleanNameit is not a SQLEntity property:

...keypath cleanName not found in entity <NSSQLEntity Artist id=1>

I know that I can keep a clean name in the store, but it seems wrong to me. One new attribute just so that the name is not prefixed? Really?

So instead, I tried to subclass NSSortDescriptor using the special compareObject: toObject: implementation method:

- (NSComparisonResult)compareObject:(Artist*)artist1 toObject:(Artist*)artist2 {

 NSString *cleanString1 = [artist1.name stringByReplacingOccurrencesOfString:@"the " withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [artist1.name length])];
 NSString *cleanString2 = [artist2.name stringByReplacingOccurrencesOfString:@"the " withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [artist2.name length])];

 return [artist1.cleanName compare:artist2.cleanName options:NSCaseInsensitiveSearch];
}

It works when I add a new artist, say "The Beatles" to my store. The artist is sorted as The Beatles and displayed in my section β€œB”. But as soon as I left the application and restarted it, I get the following error, and the table view remains empty:

sectionIndex A for Apparat
sectionIndex B for Bonobo
sectionIndex M for Misteur Valaire
sectionIndex M for Moderat
sectionIndex P for Paul Kalkbrenner
sectionIndex R for RΓΆyksopp
sectionIndex B for The Beatles
NSFetchedResultsController ERROR: The fetched object at index 6 has an out of order section name 'R. Objects must be sorted by section name'

As you can see from what I am registering, the section headings are good (the Beatles section heading is B, as it should be). But the sorting is broken, because this record should be right in front of Bonobo.

Any idea how to fix this?

+5
source share
1

, "cleanName" - " ".

+3

All Articles