【发布时间】:2015-11-03 13:36:07
【问题描述】:
我正在尝试过滤一个 JSON 填充的 UITableView,到目前为止,我已经尝试了 3 或 4 个非常好的教程,但是当我按下 SearchBar 时,我都遇到了同样的错误。
由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'不能使用 in/contains 运算符 与集合 MakeItWork.Repository(不是集合'
与我看到的教程唯一不同的是我的数组在另一个文件上,我从那里调用它。
Repository.swift
class Repository {
var name: String?
var releaseDate: String?
var gameImage: String?
var id: String?
init(json: NSDictionary) {
self.name = json["name"] as? String
self.releaseDate = json["release_date"] as? String
self.gameImage = json["image"] as? String
self.id = json["_id"] as? String
}
}
还有 GameTableViewController.swift
var games = [Repository]()
var filteredTableData = [String]()
var shouldShowSearchResults = false
var searchController: UISearchController!
func configureSearchController() {
// Initialize and perform a minimum configuration to the search controller.
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search here..."
searchController.searchBar.delegate = self
searchController.searchBar.sizeToFit()
// Place the search bar view to the tableview headerview.
self.tableView.tableHeaderView = searchController.searchBar
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchString = searchController.searchBar.text!
filteredTableData.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@",searchString)
let array = (games as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
self.tableView.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if shouldShowSearchResults {
return filteredTableData.count
}
else {
return games.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "GameTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! GameTableViewCell
if (shouldShowSearchResults) {
cell.nameLabel?.text = filteredTableData[indexPath.row]
return cell
}
else {
cell.nameLabel?.text = games[indexPath.row].name
cell.releaseDateLabel?.text = games[indexPath.row].releaseDate
if let url = NSURL(string: self.games[indexPath.row].gameImage!) {
cell.photoImageView?.hnk_setImageFromURL(url)
}
}
return cell
}
我在 updateSearchResultsForSearchController 的开头放置了一个断点,我注意到每次按下 UISearchBar 时,在崩溃之前,它都会使用 null searchString 进行搜索循环,因为我还没有在里面输入任何内容。这正常吗? 我检查的最后一个教程是 http://www.ioscreator.com/tutorials/add-search-table-view-tutorial-ios8-swift 。 我在这里错过了什么?
编辑:我认为 UISearchBar 在我调用UISearchResultsUpdating 时一直保持更新是正常的。
【问题讨论】:
标签: ios json swift uitableview uisearchbar