0

I am searching a CoreData entity by an attribute with a BEGINSWITH predicate. Now I would like to sort the results by relevance, so that direct matches appear first.

Example search string:

"star"

Result list:

"star" # <- exact match should be first
"starship"
"stargazer"

I have a CoreData fetch request like this:

NSString *stringFromSearchField;
NSFetchRequest *fr =[NSFetchRequest fetchRequestWithEntityName:@"SearchWord"];
fr.predicate = [NSPredicate predicateWithFormat:@"(word beginswith %@)", stringFromSearchField];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"Exact matches first, please..." ascending:YES];
fr.sortDescriptors = @[sortDescriptor];

I am aware that I could copy the results from my NSFetchedResultsController into a mutable array and sort in code, but I would like to avoid that if possible.

So is there any way I could archive this? Maybe some smart change in the data model or a predicate trick?

de.
  • 7,068
  • 3
  • 40
  • 69
  • 1
    I think sorting by length should work. Something like `"word.length"` – de. Feb 02 '16 at 11:11
  • ok, so what happened when you tried that ? – Wain Feb 02 '16 at 13:39
  • It doesn't work just like that. I'll investigate later, maybe it's just the syntax. Worst case I'd have to create a column that stores the length. – de. Feb 02 '16 at 14:21
  • 1
    Ok, so it *does* work for my case. The exact match is first. I'll put together an answer to my own question. – de. Feb 02 '16 at 14:40

1 Answers1

0

I have figured out a way to do this. I found a hint here: https://stackoverflow.com/a/31316010/921573

The trick is to sort by length. The exact match necessarily hase the smallest length value.
So my sort descriptor looks like this:

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"word.length"
                                                     ascending:YES];
Community
  • 1
  • 1
de.
  • 7,068
  • 3
  • 40
  • 69