iosswiftrealmbackground-threaduisearchbardelegate

How to fix this issue `Realm accessed from incorrect thread.` in swift 4


I tried to debug and trace what line the error occur , and I found out the error occur after reading the print(tcb_filteredArray) and I tried to put the print(tcb_filteredArray) below the self.tableView.reloadData() and make a debug and trace it again and it still error occur in print(tcb_filteredArray)

My search filtering code

        let realm = try! Realm()
        let tcb = realm.objects(TrialCourtBranches.self)
        let tcb_safe = ThreadSafeReference(to: tcb)
        DispatchQueue.global(qos: .userInitiated).sync {
            guard let filtered = realm.resolve(tcb_safe) else{ return }
            tcb_filteredArray = filtered.filter({ $0.branch_name.lowercased().contains(searchText.lowercased()) || ($0.loc?.pc?.province.lowercased().contains(searchText.lowercased()))! || ($0.loc?.pc?.city_municipality.lowercased().contains(searchText.lowercased()))! || $0.office_no.lowercased().contains(searchText.lowercased())})
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }

Solution

  • This is the correct answer

    searchBar.rx.text.orEmpty.debounce(0.3, scheduler: MainScheduler.instance)
            .distinctUntilChanged()
            .filter { !$0.isEmpty }
            .observeOn(MainScheduler.instance)
                .subscribe(onNext: { (data) in
                    let realm = try! Realm()
                    let tcb = realm.objects(TrialCourtBranches.self)
                    let predicate = NSPredicate(format: "(branch_name CONTAINS[c] %@) OR (office_no CONTAINS[c] %@) OR (loc.pc.city_municipality CONTAINS[c] %@) OR (loc.pc.province CONTAINS[c] %@) OR (loc.address1 CONTAINS[c] %@)",data.lowercased(),data.lowercased(),data.lowercased(),data.lowercased(),data.lowercased())
                    tcb_filteredArray = tcb.filter(predicate)
                    self.tableView.reloadData()
                }, onError: { (errorResult) in
                    print(errorResult)
                }, onCompleted: {
                    print("onCompleted")
                }, onDisposed: {
                    print("onDisposed")
                })
            .disposed(by: bag)