Search code examples
iosswiftuitableviewnspredicatensfetchrequest

Extra argument 'predicate' in call in Swift


func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
   let request: NSFetchRequest<Item> = Item.fetchRequest()
   print(searchBar.text!)

   let predicate = NSPredicate(format: "title CONTAINS[cd] %@", searchBar.text!)

   request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]

   loadItems(with: request, predicate: predicate)
}

The error is "Extra argument 'predicate' in call". And if I remove the predicate argument, then the search in the array of items does not happen. This is in a table view. You can view the full code at GitHub at the very end of the file.


Solution

  • You have to assign the predicate to the request

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
       let request: NSFetchRequest<Item> = Item.fetchRequest()
       print(searchBar.text!)
    
       request.predicate = NSPredicate(format: "title CONTAINS[cd] %@", searchBar.text!)
    
       request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]
    
       loadItems(with: request)
    }