应用程序在Swift 4的搜索栏中搜索超过2个单词时崩溃

时间:2017-10-05 10:40:13

标签: ios swift uisearchbar

当我尝试在搜索栏中输入超过2个字符时,应用程序崩溃了。尝试改变逻辑但没有用。问题可能在于空白。这是我的示例代码:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText.isEmpty {
        tableViewAdapter.fetchRequestPredicate = nil
    }
    else {
        var fullName = searchText.components(separatedBy: NSCharacterSet.whitespaces)
        for (index, name) in fullName.enumerated() {
            if name.isEmpty {
                fullName.remove(at: index)
            }
        }
        if searchText.count > 1 {
            let firstName = fullName.first
            let lastName = fullName[1]
            tableViewAdapter.fetchRequestPredicate = NSPredicate(format: "firstName BEGINSWITH[cd] %@ AND lastName BEGINSWITH[cd] %@", firstName!, lastName)
        }
        else if searchText.count == 1 {
            let firstName = fullName.first
            tableViewAdapter.fetchRequestPredicate = NSPredicate(format: "firstName CONTAINS[cd] %@ AND firstName BEGINSWITH[cd] %@ OR lastName BEGINSWITH[cd] %@", firstName!, firstName!, firstName!)
        }
    }
    tableView.reloadData()
}

1 个答案:

答案 0 :(得分:0)

如果您输入的字符数超过2个,那么如果您的文字中没有空格,您的程序将尝试访问fullName的第二个元素,即不存在

替换

if searchText.count > 1
else if searchText.count == 1

if fullName.count > 1
else if fullName.count == 1

此外,您的代码有很多力量解包。您应该避免使用它,特别是如果您的数据取决于用户输入。