I am interested in sorting an NSFetchRequest in a very particular way. In my app, the user can enter a search query. I would like to return the results sorted with items starting with the query they typed in, followed by the rest of the items that simply contains the query.
For example: The user types in "de". I would like the results to be ordered in such a way where all of the results that start with "de" are first, followed by the rest of the columns that contain "de".
Here is what I would like the results to look like:
Deathless Behemoth
Deathmark
Deathmark Prelate
Deathmask Nezumi
Deathmist Raptor
Deathpact Angel
Acid Web Spider
Careful Consideration
Hell-Bent Raider
Jhovall Rider
Living Death
I've used NSSortDescriptors for other types of searches in my app, but there doesn't seem to be a way to use it for this specific purpose.
Here is the NSPredicate I am using to currently get the result that I want, but not in the specific order that I am looking for:
let namePredicate = NSCompoundPredicate(
type: .or,
subpredicates: [
NSPredicate(format: "name BEGINSWITH[cd] %@", name),
NSPredicate(format: "name CONTAINS[cd] %@", name)
]
)