Search Bar delegate

swift

#1

Доброго дня) У меня есть данные, сохраненный в CoreData я пытаюсь сделать поиск по этим данным, не получается создать SearchBar, на строчку searchBar.delegate = self выдает ошибку…

class DataBase: UITableViewController {

    var persons : [Friend]?
    var searchPersons = [Friend]()
    var isSearch = false
    
    @IBOutlet weak var searchBar: UISearchBar!
    override func viewDidLoad() {
        super.viewDidLoad()
        persons = fetchAllPerson()
       // searchBar.delegate = self
         self.clearsSelectionOnViewWillAppear = false

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return isSearch ? searchPersons.count : persons?.count ?? 0
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .value1, reuseIdentifier: "personCell")
            cell.textLabel?.text = isSearch ? searchPersons[indexPath.row].name : persons?[indexPath.row].name
            cell.detailTextLabel?.text = isSearch ? searchPersons[indexPath.row].profileImageName ?? "img" : persons?[indexPath.row].profileImageName ?? "img"
        return cell
    }
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            getContext().delete(lookup(indentification: (persons?[indexPath.row].name)!)!)
            persons?.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
            save()
        }
    }
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
    }
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //CLICK!
    }
}
extension DataBase : UISearchBarDelegate{
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        isSearch = false
        
    }
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        
    }
    func onSearch(str :String) {
        if str.isEmpty {
            isSearch = false
        }else{
            isSearch = true
            searchPersons.removeAll()
            for person in persons! {
                let index = person.name?.range(of: str.lowercased())
                if index?.isEmpty != nil {
                searchPersons.append(person)
                }
            }
        }
        self.tableView.reloadData()
    }
}


#2

Какую ошибку? (20 символов)


#3

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)


#4

Подключите аутлет


#5

Я так делала, не помогает(


#6

Не может быть, проверьте еще раз) или скиньте проект


#7

Несколько раз пробовала… https://yadi.sk/d/T-UAN0uW3M6N5K


#8

У вас там всё очень сложно, вы контроллер грузите через код и при этом хотите сториборд)
Вот поправил https://yadi.sk/d/LdnVv6dX3M6SCV


#9

Спасибо большое, работает)