我正在学习使用Search Bar和数据过滤实现TableView.所以,我的故事板中有以下内容: 我的UITableViewController连接到以下SearchTableViewController.swift类,如下所示: import UIKitclass SearchTableViewControll
我的UITableViewController连接到以下SearchTableViewController.swift类,如下所示:
import UIKit class SearchTableViewController: UITableViewController, UISearchResultsUpdating { // table view controller properties let appleProducts = ["Mac", "iPhone", "Apple Watch", "iMac", "iPad"] var filteredAppleProducts = [String]() var resultSearchController = UISearchController() override func viewDidLoad() { super.viewDidLoad() // Configure result search controller self.resultSearchController = UISearchController(searchResultsController: nil) self.resultSearchController.searchResultsUpdater = self self.resultSearchController.dimsBackgroundDuringPresentation = false self.resultSearchController.searchBar.sizeToFit() self.resultSearchController.searchBar.placeholder = "Search Products" self.tableView.tableHeaderView = self.resultSearchController.searchBar self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (self.resultSearchController.active) { return self.filteredAppleProducts.count } else { return self.appleProducts.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell if (self.resultSearchController.active) { cell.textLabel?.text = self.filteredAppleProducts[indexPath.row] } else { cell.textLabel?.text = self.appleProducts[indexPath.row] } return cell } func updateSearchResultsForSearchController(searchController: UISearchController) { self.filteredAppleProducts.removeAll(keepCapacity: false) let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!) let resultArray = (self.appleProducts as NSArray).filteredArrayUsingPredicate(searchPredicate) self.filteredAppleProducts = resultArray as! [String] self.tableView.reloadData() } }
运行正常,过滤按预期工作:
但是,当应用程序在模拟器中运行时,我在调试窗口中收到以下警告:
2015-09-07 00:02:46.116 TableViewSearch[2415:68217] Attempting to load
the view of a view controller while it is deallocating is not allowed
and may result in undefined behavior ()
任何想法如何解决这一问题?
我花了一整天时间来理解这个问题……有人说它与导航控制器问题有关,而其他人说这是一个小问题.虽然这可能不是正确答案,但希望我能给出一些暗示.如果您认为这不是一个正确的方法,请告诉我.谢谢.我的情况如下(因为不同的设计,我认为.)
var resultSearchController: UISearchController!()
然后,我必须在下面添加.
self.resultSearchController.loadViewIfNeeded()