2017-10-05 56 views
0

當我嘗試在搜索欄中輸入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() 
} 

回答

0

如果輸入超過2個字符,你的程序將嘗試訪問的fullName第二個元素,這是不存在如果你沒有你的空白文本。

更換

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

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

此外,你的代碼有很多的力展開。您應該避免使用它,特別是如果您的數據取決於用戶輸入。

+0

沒有。但是我仍然得到同樣的錯誤。 –

+0

哪條線路導致崩潰?如果你還沒有設置[異常斷點](https://stackoverflow.com/questions/17802662/exception-breakpoint-in-xcode)。 – the4kman