title: Realm Swift background search
body: <p>I have a realm database in my app, containing a list of ~2000 users.</p>
  
  <p>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.</p>
  
  <p>Now it's a lot better, but I'm not 100% sure that it's the best way to do this.</p>
  
  <p>Can you suggest any other solutions, if you have any better ?</p>
  
  <p>Here's the sample code I use :</p>
  
  <pre><code>func filterUsers(searchText:String,completion: (result: Array&lt;User&gt;) -&gt; ()){
  
      var IIDS = Array&lt;String&gt;()
  
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -&gt; 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(), { () -&gt; Void in
  
              let realm = try! Realm()
              let foundUsers = Array(realm.objects(User).filter("IID IN {\(IIDS.joinWithSeparator(","))}"))
              IIDS.removeAll()
              completion(result: foundUsers)
          })
      })
  }
  </code></pre>