2015-09-14 58 views
0

目前我正在嘗試爲我的tableView設置一個搜索欄。我想用NSPredicate過濾用戶的輸入,以顯示來自結構對象數組的過濾數據。Swift - 使用UISearchController和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

非常感謝!

回答

0

所以經過多次環顧四周,我發現,這樣的情況下一個更好的方法是簡單地使用.filter()和.rangeOfString()來解決這個

theArray.filter() { $0.json?.rangeOfString(searchQuery, options: .CaseInsensitiveSearch) != nil} 

雖然沒有使用NSPredicate ,這對我目前的設置來說似乎更容易實現。