iOS Realm Filter objects in a list of a relationship

前端 未结 3 1044
挽巷
挽巷 2020-12-31 04:54

I have three objects nested via lists like this:

class Canteen: Object {

        dynamic var name: String?
        let lines = List()
}

class L         


        
3条回答
  •  天命终不由人
    2020-12-31 05:24

    Realm allows it to use functions as parameter for the filtering. So this is my solution which im currently using.

    The two filter functions:

    func vegetarianFilter(_ meal: Meal) -> Bool {
    
            if showVegetarianOnly {
                if(meal.veg || meal.vegan){
                    return true
                }
    
                return false
            }
    
            return true
    }
    
    func filterEmptyLines(_ line: Line) -> Bool {
    
           if(line.meals.filter(vegetarianFilter).count > 0){
               return true
           }
    
           return false
    }
    

    The functions filter all meals which are not vegetarian or vegan when the user has selected showVegetarianOnly = true. Also it filters all lines which than have no meal left (nothing is vegetarian or vegan).

    Most important functions of the TableView:

        override func numberOfSections(in tableView: UITableView) -> Int {
                return canteenDay?.lines.filter(filterEmptyLines).count ?? 0
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                return canteenDay?.lines.filter(filterEmptyLines)[section].meals.filter(vegetarianFilter).count ?? 0
        }
    
       override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
            let cell = UITableViewCell()
    
            let meal = canteenDay!.lines.filter(filterEmptyLines)[indexPath.section].meals.filter(vegetarianFilter)[indexPath.row]
    
            cell.textLabel?.text = meal.meal
    
           return cell
        }
    

提交回复
热议问题