Retrive Core Data objects with case-insensitive comparison

Jun 1, 2012 · Follow on Twitter and Mastodon objc

I’m currently building an iOS app that uses core data for data persistency. It works great, but as I started retrieving entities by name, I noticed that they arrived in a strange order:

  • Object 1
  • Object 3
  • object 2

There is probably some case-sensitive sorting issue showing its ugly face, right. This is the code I used to sort the data:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];

The solution was to add selector to the sort, like this:

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

And voilá - the list will now look like this:

  • Object 1
  • object 2
  • Object 3

This also works for local-specific characters, like Swedish å, ä and ö.

Discussions & More

Please share any ideas, feedback or comments you may have in the Disqus section below, or by replying on Twitter or Mastodon..

If you found this text interesting, make sure to follow me on Twitter and Mastodon for more content like this, and to be notified when new content is published.

If you like & want to support my work, please consider sponsoring me on GitHub Sponsors.