How do I work with realm notification if result is updated after notification is initialized?

谁都会走 提交于 2019-12-04 20:59:39

You overwrite results in updateSearchResults(). Notification and notificationToken is tied to specific Results object and query. So if you overwrite results by another query, you should stop the previous notification, then re-add notification to the new results object.

So updateSearchResults() method should be like the following:

func updateSearchResults(for searchController: UISearchController) {
    let searchText = searchController.searchBar.text!
    if searchText.isEmpty == false {
        results = results?.realm?.objects(Person.self).filter("active = '1'")
        results = results?.filter("name BEGINSWITH[c] %@ OR lastName CONTAINS[c] %@", searchText, searchText)
        results = results?.sorted(byProperty: "name", ascending: true)
    }
    else {
        results = results?.realm?.objects(Person.self).filter("active = '1'").sorted(byProperty: "name", ascending: true)
    }

    notificationToken.stop()
    notificationToken = results?.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
        guard let tableView = self?.tableView else { return }
        switch changes {
        case .initial:
            tableView.reloadData()
            break
        case .update(_, let deletions, let insertions, let modifications):
            tableView.beginUpdates()

            tableView.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) }, with: .automatic)

            tableView.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
            tableView.reloadRows(at: modifications.map { IndexPath(row: $0, section: 0) }, with: .automatic)
            tableView.endUpdates()
            break
        case .error(let error):
            print("Error: \(error)")
            break
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!