how do I make my sort function working to actually display the sorted books in the tableview

Viewed 45

Hi tried to create a sort button with the CocoaPods Dropdown, the code doesn't show any error and the menu works, but if I click on the button nothing is happening.

    dropDown.selectionAction = { [weak self] (index: Int, item: String) in //8
      guard let _ = self else { return }
      sender.setTitle(item, for: .normal) //9
       
        let realm = try! Realm()
        var books = realm.objects(Book.self).sorted(byKeyPath: "title", ascending: false)
    
        if item == "sort by author" {
            func filterResultsbyauthor(searchString: String){
                 let predicate = NSPredicate(format: "author BEGINSWITH [c]%@", searchString)
                books = realm.objects(Book.self).filter(predicate).sorted(byKeyPath:"author", ascending: true)
                self?.tableview.reloadData()
            }
        }
    }
1 Answers

Error is probably here:

func filterResultsbyauthor(searchString: String){
    let predicate = NSPredicate(format: "author BEGINSWITH [c]%@", searchString)
    books = realm.objects(Book.self).filter(predicate).sorted(byKeyPath:"author", ascending: true)
    self?.tableview.reloadData()
}

You defined a function, but never called it.

You can either:

  1. Call the function
func filterResultsbyauthor(searchString: String){
    let predicate = NSPredicate(format: "author BEGINSWITH [c]%@", searchString)
    books = realm.objects(Book.self).filter(predicate).sorted(byKeyPath:"author", ascending: true)
    self?.tableview.reloadData()
}

filterResultsbyauthor(searchString: "Your search string") /// here!
  1. Remove the function declaration and just make it a chunk of code
let predicate = NSPredicate(format: "author BEGINSWITH [c]%@", "Your search string")
books = realm.objects(Book.self).filter(predicate).sorted(byKeyPath:"author", ascending: true)
self?.tableview.reloadData()
Related