I have a realm database in my app, containing a list of ~2000 users.
A tableview displays these users, and a search bar allows to filter them (on 6 different properties of each user). This operation was blocking the UI, so I put it in a background thread.
Now it's a lot better, but I'm not 100% sure that it's the best way to do this.
Can you suggest any other solutions, if you have any better ?
Here's the sample code I use :
func filterUsers(searchText:String,completion: (result: Array<User>) -> ()){
var IIDS = Array<String>()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
let predicate1 = NSPredicate(format: "firstName contains[c] %@", searchText)
let predicate2 = NSPredicate(format: "lastName contains[c] %@", searchText)
let bgRealm = try! Realm()
bgRealm.beginWrite()
//Filter the whole list of users
var results = Array(bgRealm.objects(User)).filter {
//One user object by one
let usr:User = $0
//Reset the value by default
usr.searchResultField = ""
if predicate1.evaluateWithObject(usr) {
usr.searchResultField = "firstNameORlastName"
return true
}
else if predicate2.evaluateWithObject(usr) {
usr.searchResultField = "IID"
}
return false
};
try! bgRealm.commitWrite()
for usr in results {
IIDS.append("'\(usr.IID)'")
}
results.removeAll()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let realm = try! Realm()
let foundUsers = Array(realm.objects(User).filter("IID IN {\(IIDS.joinWithSeparator(","))}"))
IIDS.removeAll()
completion(result: foundUsers)
})
})
}