Swift - 使用UISearchController和NSPredicate搜索结构数组

时间:2015-09-14 01:56:15

标签: swift nsarray nspredicate uisearchcontroller swift-array

目前我正在尝试为我的tableView设置搜索栏。我想用NSPredicate过滤用户的输入,以显示结构对象数组中的过滤数据。

但是当我尝试在这样的数组上调用.filteredArrayUsingPredicate()时,我收到以下错误[Course] is not convertible to 'NSArray'

以下是我的代码和回购的链接。我也对任何更好的方法都持开放态度。

import UIKit
import SwiftyJSON

class CourseTableViewController: UITableViewController, UISearchResultsUpdating {

    var allCourses: [Course] = [Course]()

    var searchArray: [Course] = [Course]() {
        didSet {
            self.tableView.reloadData()
        }
    }

    var resultSearchController = UISearchController()

    override func viewDidLoad() {
        super.viewDidLoad()
        retrieveCourses()
        configureView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func configureView() {
        tableView.rowHeight = 50

        // Search Controller Initialization
        self.resultSearchController = UISearchController(searchResultsController: nil)
        resultSearchController.searchResultsUpdater = self
        resultSearchController.hidesNavigationBarDuringPresentation = false
        resultSearchController.dimsBackgroundDuringPresentation = false
        resultSearchController.searchBar.searchBarStyle = .Minimal
        resultSearchController.searchBar.sizeToFit()
        self.tableView.tableHeaderView = resultSearchController.searchBar
    }

    func retrieveCourses() {
        APIService.getAllCourses() { (data) -> Void in
            for courseIndex in data {
                var course: Course = Course(courseJSON: courseIndex.1)
                self.allCourses.append(course)
                println("Course Index: " + String(self.allCourses.count))
            }

            self.sortAllCourses()
        }
    }

    func sortAllCourses() {
        allCourses.sort() {$0.abbr < $1.abbr}
        self.tableView.reloadData()
    }

    // MARK: - Search

    func updateSearchResultsForSearchController(searchController: UISearchController) {
        self.searchArray.removeAll(keepCapacity: false)

        let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text)

        // ERROR is on this line
        let filteredArray: Array = (allCourses as NSArray).filteredArrayUsingPredicate(searchPredicate)

        self.searchArray = filteredArray as [Course]
    }

    // Full tableView code can be found in the repo
}

链接:https://github.com/classmere/app/tree/feature/issue/1/implementSearch

非常感谢!

1 个答案:

答案 0 :(得分:0)

所以经过多次调查后,我发现对于这种情况更好的方法是简单地使用.filter()和.rangeOfString()来解决这个问题

1.0

虽然未使用NSPredicate,但这对我当前的设置来说似乎更容易实现。