1

My app is using a Realm database to store a number of items. With a SearchBar, I search (case insensitive) for an item that may already be stored in the database (and if not, it will be added). The item names often contain one of the swedish characters and my problem is that when searching for a swedish character (å, ä or ö), the filter passes "a" or "o" as well, i.e. a search for "ä" results in a/A, å/Å and ä/Ä.

extension ItemsVC: UISearchResultsUpdating {

    func updateSearchResults(for searchController: UISearchController) {

        if isFiltering() {
            let predicate = NSPredicate(format: "name CONTAINS[cd] %@ AND NONE owners.name == %@", searchController.searchBar.text!, (category?.name)!)
            items = realm.objects(Item.self).filter(predicate).sorted(byKeyPath: "name", ascending: true)

            tableView.reloadData()
        }
    }
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Stalle
  • 67
  • 1
  • 6

1 Answers1

0

This seems like a bug in Realm's filter implementation. If you supply the same predicate to an NSArray containing the same Objects, those return the correct results.

class Person: Object {
    @objc dynamic var name:String = ""
}

let people = stringsWithAccents.map{Person(value: ["name":$0])}
try realm.write {
    realm.add(people)
}

let namePredicate = NSPredicate(format: "name CONTAINS[c] %@", searchString)
let foundPeople = realm.objects(Person.self).filter(namePredicate)
print(foundPeople) // Results<Person> <0x7fec74c13060> ( [0] Person { name = á; })

print((people as NSArray).filtered(using: namePredicate)) // [Person { name = á;},Personn { name = Á;}]

I've opened an issue on RealmCocoa's GitHub.

In the meantime as a workaround you can manually check for both the lowercased and uppercased version:

let customCaseInsentiveNamePredicate = NSPredicate(format: "name CONTAINS %@ OR name CONTAINS %@", searchString, searchString.uppercased())
print(realm.objects(Person.self).filter(customCaseInsentiveNamePredicate))
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116