-1

I'm using Swift to create an iOS app, and I have a function that gets a list of all files in your documents directory and puts them in an NSMutableArray.

I'm searching on how to use a SearchBar to filter the items in a table view.

Is it possible to either put all items in an NSMutableArray into a regular array for me to use for this, or is it possible to modify the code below to work with an NSMutableArray

The tutorial:

  var data = ["San Francisco","New York","San Jose","Chicago","Los Angeles","Austin","Seattle"]
var filtered:[String] = []

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

    filtered = data.filter({ (text) -> Bool in
        let tmp: NSString = text
        let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
        return range.location != NSNotFound
    })
    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
    self.tableView.reloadData()
}
itsMagnus
  • 1
  • 1
  • I didnt quite understand what you're asking for based on your code and what you're saying. – Arbitur Mar 25 '15 at 23:50
  • I'm trying to use a UISearchBar with an NSMutableArray. All the tutorials I find require a regular array. – itsMagnus Mar 25 '15 at 23:58
  • I higly recommend you leaving the old stuff behind and start using the Swift arrays and dictionaries. var arr = [AnyObject]() == NSMutableArray() – Arbitur Mar 26 '15 at 00:00
  • var filtered can be let filtered, won't be a problem. If that's what you are asking. – Shubham Naik May 24 '17 at 09:14

1 Answers1

2

If you want to convert your NSMutableArray to a normal NSArray, then there are a lot of sources on how to do this. On StackOverflow, there are a number of questions that ask the same, such as this rather active question. Swift-specific code can be found in Apple's reference. To summarize, you can initialize a new, non-mutable array from another array (e.g. an NSMutableArray) like this:

var nonMutableArray = mutableArray as AnyObject as [String]

Source.

If you are looking for a resource on how to implement searching in a UITableView, check out a page like this.

Community
  • 1
  • 1
Erik S
  • 1,939
  • 1
  • 18
  • 44
  • I'm trying to filter using the solution you gave me, and while trying to use the index path in the table, I'm getting "[String] does not have a member named 'objectAtIndex'" – itsMagnus Mar 25 '15 at 23:57
  • thats because a Swift array doesnt have that method, it uses subscriptions eg: arr[12] == oldArr.objectAtIndex(12) – Arbitur Mar 26 '15 at 00:02
  • Which part? Converting it to a non-mutable array, or implementing the searchbar? Typically, you will want to split 2 questions like this in seperate questions on StackOverflow to improve the number of answers you potentially get by having specific questions. – Erik S Mar 26 '15 at 07:28