应用程序在Swift 4的搜索栏中搜索超过2个单词时崩溃
问题描述:
当我尝试在搜索栏中输入2个以上的字符时,应用程序崩溃。试图改变逻辑但没用。问题可能出在空白处。下面是我的示例代码:应用程序在Swift 4的搜索栏中搜索超过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()
}
答
如果输入超过2个字符,你的程序将尝试访问的fullName
第二个元素,这是不存在如果你没有你的空白文本。
更换
if searchText.count > 1
else if searchText.count == 1
与
if fullName.count > 1
else if fullName.count == 1
此外,你的代码有很多的力展开。您应该避免使用它,特别是如果您的数据取决于用户输入。
没有。但是我仍然得到同样的错误。 –
哪条线路导致崩溃?如果你还没有设置[异常断点](https://stackoverflow.com/questions/17802662/exception-breakpoint-in-xcode)。 – the4kman