搜索和过滤阵列火力基础数据 SWIFT3.



我的应用程序在搜索栏中搜索文本时崩溃并显示错误:thread1:signal SIGABRT 可能是问题更新搜索结果(( 方法?还是数组类型?我是初学者,有快速的想法吗?

@IBOutlet weak var tableView: UITableView!
var data = [Any]()
var ref:FIRDatabaseReference!
// Filter Data from Firebase
var filteredData = [Any]()
// Declare searchBar
let searchController = UISearchController(searchResultsController: nil)

//is the device landscape or portrait
var isPortraid = true
@IBOutlet weak var bannerView: GADBannerView!

func fetchDataFromFirebase(){
    EZLoadingActivity.show("caricamento...", disableUI: true)
    ref = FIRDatabase.database().reference()
    ref.observe(.value, with: { (snapshot) in
        let dataDict = snapshot.value as! NSDictionary
        self.data = dataDict["data"] as! [Any]
        self.filteredData = self.data
        print ("Sacco di merda:(self.filteredData)")
        self.tableView.reloadData()
        EZLoadingActivity.hide()
    })
}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    fetchDataFromFirebase()
    //  Implement searchBar
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    tableView.tableHeaderView = searchController.searchBar


    NotificationCenter.default.addObserver(self, selector: #selector(MainViewController.orientationChanged), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

}

//TableView Data Source and Delegate

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for:indexPath) as! MainScreenTableViewCell
    let rowData = self.filteredData[indexPath.row] as! NSDictionary
    let imageName  = rowData["imageName"] as! String
    cell.backgroundImageView.image = UIImage(named: imageName)
    let label = rowData["categoryName"] as! String
    cell.mealCategoryLabel.text = label
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
    let categoryViewController = storyboard.instantiateViewController(withIdentifier: "CategoryViewController") as! CategoryViewController
    let rowData = self.data[indexPath.row] as! NSDictionary
    categoryViewController.categoryTitle = rowData["categoryName"] as! String
    let categoryData = rowData["category"] as! [Any]
    categoryViewController.data = categoryData
    self.navigationController?.pushViewController(categoryViewController, animated: true)
}


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if isPortraid {
    return UIScreen.main.bounds.height/3
    } else {
        return UIScreen.main.bounds.height/1.2
    }
}

更新搜索方法

func updateSearchResults(for searchController: UISearchController) {
    if searchController.searchBar.text! == ""{
        filteredData = data
    } else {
        filteredData = data.filter{($0 as AnyObject).contains(searchController.searchBar.text!)}
    }
    self.tableView.reloadData()
}
if searchController.searchBar.text! == ""

这几乎可以肯定是罪犯。 UI 对象上的 text 属性在为空时通常为 nil,因此当您强制解包它时,应用会崩溃。 你永远不应该强行打开某些东西,除非你绝对确定它永远不会是零的。

有几种不同的方法可以解决这个问题,这基本上相当于在你对它做任何事情之前确保text不是零。

就个人而言,我会重写 if 语句以解开非空情况的可选包:

if let text = searchController.searchBar.text, text != "" {
    filteredData = data.filter{($0 as AnyObject).contains(text)}
} else {
    filteredData = data
}

您也可以使用零合并:

if (searchController.searchBar.text ?? "") == ""

但就我个人而言,我更喜欢写它以避免强制展开,即使您确定它不是零,所以我会推荐第一个。

最新更新