Daniel Storch Daniel Storch - 8 days ago 5
iOS Question

iOS realm multiple filter based on if else statements

Is it possible to have multiple filters which are used based on the outcome of them?

I want to filter a list of university courses based on their name and check if the list of filtered courses is > 0. If not, i automatically get them all.

This is what im doing right now, giving the user a button to show all if the view is empty:

override func viewDidLoad() {

if let courseName = GetCourseName(){
let predicate = NSPredicate(format: "name contains %@", courseName)
courses = try! RealmManager.realm().objects(Course.self).filter(predicate).sorted("name")
token = try! RealmManager.realm().objects(Course.self).filter(predicate).addNotificationBlock({ changes in
self.tableView.reloadData()
})

self.navigationItem.rightBarButtonItems = [UIBarButtonItem(title: "Show all", style: .Plain, target: self, action: #selector(showAll(_:)))]

}else{
courses = try! RealmManager.realm().objects(Course.self).sorted("name")
token = try! RealmManager.realm().objects(Course.self).addNotificationBlock({ changes in
self.tableView.reloadData()
})
}
}

func showAll(sender:AnyObject)
{
courses = try! RealmManager.realm().objects(Course.self).sorted("name")
token = try! RealmManager.realm().objects(Course.self).addNotificationBlock({ changes in
self.tableView.reloadData()
})

self.navigationItem.rightBarButtonItems?.removeAll()
}

Answer

It sounds like something like this should work. Basically, if there is a course name, set courses to the filtered results. Then, if courses is nil or empty, set it to show all.

override func viewDidLoad() {
    if let courseName = GetCourseName(){
        let predicate = NSPredicate(format: "name contains %@", courseName)
        courses = try! RealmManager.realm().objects(Course.self).filter(predicate).sorted("name")
    }

    if course == nil || course.isEmpty {
        courses = try! RealmManager.realm().objects(Course.self).sorted("name")
    }

    token = courses.addNotificationBlock({ changes in
        self.tableView.reloadData()
    })
}