Swift UISearchController wired up in Core Data Project, app runs, but search not updating

拟墨画扇 提交于 2019-12-03 00:24:08

The problems lie in your tableView datasource methods: numberOfSectionsInTableview:, tableView:numberOfRowsInSection:, and tableView:cellForRowAtIndexPath:. You need each of those methods to return different results if the searchPredicate is not nil - much like your tableView:commitEditingStyle: method does. I would make filteredObjects an instance property (defined at the start of the class) so that all those methods can access it:

var filteredObjects : [Note]? = nil

Now, when the search text changes, you want to rebuild the filteredObjects array. So in updateSearchResultsForSearchController, add a line to recompute it based on the new predicate:

    if let searchText = searchText {
        searchPredicate = NSPredicate(format: "noteBody contains[c] %@", searchText)
        filteredObjects = self.fetchedResultsController.fetchedObjects?.filter() {
            return self.searchPredicate!.evaluateWithObject($0)
        } as [Note]?
        self.tableView.reloadData()
        println(searchPredicate)
    }

I would also recommend (for simplicity) that when you activate the search, the results are displayed all in one section (otherwise you have to work out how many sections your filtered results fall into - possible but tiresome):

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    if searchPredicate == nil {
        return self.fetchedResultsController.sections?.count ?? 0
    } else {
        return 1
    }
}

Next, if the searchPredicate is not nil, the number of rows in the section will be the count of filteredObjects:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if self.searchPredicate == nil {
        let sectionInfo = self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo
        return sectionInfo.numberOfObjects
    } else {
        return filteredObjects?.count ?? 0
    }
}

Finally, if the searchPredicate is not nil, you need to build the cell using the filteredObjects data, rather than the fetchedResultsController:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
    if searchPredicate == nil {
        self.configureCell(cell, atIndexPath: indexPath)
        return cell
    } else {
        // configure the cell based on filteredObjects data
        ...
        return cell
    }
}

Not sure what labels etc you have in your cells, so I leave it to you to sort that bit.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!