搜索显示控制器导致崩溃

时间:2015-04-12 12:46:03

标签: uitableview swift uisearchbar uisearchdisplaycontroller

我正在尝试使用TableView设置searchBar,以便我可以通过表视图进行过滤,我试图以编程方式完成所有操作。虽然我的代码不断发回错误:unexpectedly found nil while unwrapping an Optional value。错误在func numberOfRowsInSection内,我已经标记过了。它与SearchDisplayController有关,它说它是零我认为?代码:

struct UserMatches {
    var finalMatchesName : String
    var finalMatchesAge : Int
    var finalMatchesLocation : PFGeoPoint
    var finalMatchesImage : NSData
}

class Matches: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate {

    var tableView = UITableView()
    var searchBar = UISearchBar()

    var userMatches = [UserMatches]()
    var filterUsers = [UserMatches]()

    override func viewDidLoad() {
        super.viewDidLoad()
        createTableView()
    }

    func filterContentForSearchText(searchText: String) {
        self.filterUsers = self.userMatches.filter({(user1: UserMatches) -> Bool in
            let stringMatch = user1.finalMatchesName.rangeOfString(searchText)
            return (stringMatch != nil)
        })
    }

    func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
        self.filterContentForSearchText(searchString)
        return true
    }

    func createTableView() {
        tableView.sizeToFit()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

        searchBar.sizeToFit()
        searchBar.delegate = self
        searchBar.showsScopeBar = true
        searchBar.searchBarStyle = UISearchBarStyle.Minimal
        searchBar.showsCancelButton = true
        searchBar.returnKeyType = UIReturnKeyType.Search
        tableView.tableHeaderView = searchBar

        var searchDispCont = UISearchDisplayController(searchBar: searchBar, contentsController: nil)
        searchDispCont.delegate = self;
        searchDispCont.searchResultsDataSource = self;
        searchDispCont.searchResultsDelegate = self;

        self.view.addSubview(tableView)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.searchDisplayController!.searchResultsTableView {  //fatal error: unexpectedly found nil while unwrapping an Optional value 
            return self.filterUsers.count
        } else {
            return self.userMatches.count
        }
    }
}

1 个答案:

答案 0 :(得分:1)

是的,您的视图控制器的searchDisplayController属性属于UISearchDisplayController?类型(可选),nil位于tableView(_:numberOfRowsInSection:)内。当您使用!强制打开可选项时,当值为nil时,您的应用会抛出运行时异常(您正在看到的异常)。

属性为nil的原因是您以编程方式创建它并为nil参数指定contentsController。这很可能是:

var searchDispCont = UISearchDisplayController(searchBar: searchBar, contentsController: self)

这会隐式将其分配给您的视图控制器的searchDisplayController属性。

另外,值得注意的是,在iOS 8中不推荐使用UISearchDisplayControllerUISearchDisplayDelegate,因此您应该使用UISearchController