Filtering query for Realm

Viewed 109

I have a function which prints all the objects in my realm table to a table view. I would like to be able to filter these objects by their "muscle" property.

Here's my DB helper functions:

func getMusclesCount()-> Int {
    let storedExercise = realm.objects(StoredExercise.self)
    return storedExercise.count
    
}

//MARK:- getAllMuscelsNames
func getAllMusclesNames()-> [String] {
    var musclesName = [String]()
    let storedExercise = realm.objects(StoredExercise.self)
    for exercise in storedExercise {
        print("Muscle = \(exercise.muscle)")
        musclesName.append(exercise.name)
    }
    return musclesName
} 

Here's my Table View Controller class :

class TableViewController: UITableViewController {

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

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return DBHelper.shared.getAllMusclesNames().count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    if cell == nil {
        cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    }
    let muscle = DBHelper.shared.getAllMusclesNames()[indexPath.row]
    cell.textLabel?.text = muscle
    return cell
}

I've tried adding .Filter to 'let storedExercise' but I'm not sure how to set it up correctly. Any assitance would be greatly appreciated, thanks.

1 Answers

If your StoredExercise model looks like this

class StoredExercise: Object {
  @objc dynamic var muscle = ""
}

then to get all of the exercises that are for the biceps, it's this

let bicepResults = realm.objects(StoredExercise.self).filter("muscle == 'biceps'")
Related