Swift Firebase UISearchController索引超出范围

时间:2017-08-21 22:00:23

标签: swift firebase search segue uisearchcontroller

我有一个tableview,列出了我所有的"地点"来自firebase。我有一个UISearchController来显然搜索这些"地点"。问题是当我点击UISearchController但没有输入任何内容并选择一个"地点"我得到索引超出范围错误。如果我正在键入或未激活UISearchController,它就会很好。就在它处于活动状态时,不输入就是我收到错误的时候。它会在" let user = filteredUsers [indexPath.row]"

上抛出错误
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)
    if segue.identifier == "BusinessProfiles" {
        // gotta check if we're currently searching
        if self.searchController.isActive  {
            if let indexPath = tableView.indexPathForSelectedRow {
                let user = filteredUsers[indexPath.row]
                let controller = segue.destination as? BusinessProfilesViewController
                controller?.otherUser = user
            }
        } else {
            if let indexPath = tableView.indexPathForSelectedRow {
                let user = usersArray[indexPath.row]
                let controller = segue.destination as? BusinessProfilesViewController
                controller?.otherUser = user
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

正如你所说,你没有进行任何搜索并选择一个地方,对吗?如果是这样,则使用所选行的indexPath.row调用空filteredUsers[indexPath.row],该行具有正索引。因此,您必须先检查搜索是否已执行,然后再调用filteredUsers[indexPath.row],如下所示:

if !filteredUsers.isEmpty {
    if self.searchController.isActive  {
            if let indexPath = tableView.indexPathForSelectedRow {
                let user = filteredUsers[indexPath.row]

答案 1 :(得分:0)

刚添加了这个“&& searchController.searchBar.text!=”“ “纠正我的问题

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)
    if segue.identifier == "BusinessProfiles" {
        // gotta check if we're currently searching
        if self.searchController.isActive && searchController.searchBar.text != "" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let user = filteredUsers[indexPath.row]
                let controller = segue.destination as? BusinessProfilesViewController
                controller?.otherUser = user
            }
        } else {
            if let indexPath = tableView.indexPathForSelectedRow {
                let user = usersArray[indexPath.row]
                let controller = segue.destination as? BusinessProfilesViewController
                controller?.otherUser = user
            }
        }
    }
}