iPhone CoreData - How to fetch managed objects, and sorting them ignoring case?
Asked Answered
T

4

31

Does anyone know how to fetch some results sorting them alphabetically but ignoring case?

Tithable answered 6/1, 2010 at 13:23 Comment(0)
T
78

Thank you for your reply, but I need to sort the result of a simple "query" ignoring case. Your suggestion applies for searching and comparing.

SQL speaking, I need an ORDER BY firstName ASC, and this command must be case insensitive for my usage.

I have done some Googling and I ended reading the NSSortDescriptor Class reference, and I could find the answer for my question. The solution is setting a selector to the sort descriptor as follow:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES selector:@selector(caseInsensitiveCompare:)];

I hope it will be useful for more people.

Tithable answered 7/1, 2010 at 13:21 Comment(3)
Don't forget that colon after caseInsensitiveCompare:Tonneson
I tested this with SQL logging enabled. Turns out that iOS is smart enough to do the sorting in SQL instead of in memory, by putting COLLATE NSCollateNoCase, or COLLATE NSCollateLocaleSensitiveNoCase for localizedCaseInsensitiveCompare:, after ORDER BY. Tested on simulator with iOS 6, and device with iOS 7.Aversion
For those of you looking for a > xCode 7 and Swift solution: [NSSortDescriptor(key: "string", ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))]Teleprinter
R
10

If the app is localized in several languages, please consider using the localizedCaseInsensitiveCompare: selector instead of caseInsensitiveCompare. It will have the effect to avoid the letter 'é' to be after the letter 'e'.

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
Radiculitis answered 18/9, 2012 at 10:51 Comment(0)
H
5

Check out the NSPredicate programming guide, but basically use [c] to ignore case:

@"firstName BEGINSWITH[c] $FIRST_NAME"
Horologe answered 6/1, 2010 at 13:37 Comment(1)
Hey Ben, Thanks! I could find the answer for my question. I posted it here. Cheers, VFNTithable
I
4

Swift Version:

let sortDescriptor = NSSortDescriptor(key: "firstName", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare))
Interjection answered 8/3, 2017 at 17:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.