Create a two-section UITableView with items from a Realm object


#1

Hi,

In the following code I’m displaying all items from a list called groceryList without any issues, everything works fine. What I would like to do is break up the table into two sections, the first section would display all items that are active and the second section would show the items that are NOT active based on the isItemActive variable from the Item object.

What would be the best way to create a two-section UITableView with items from a Realm object?

Realm Objects:

class Item:Object{
    @objc dynamic var productName:String = ""
    @objc dynamic var isItemActive = true
    @objc dynamic var createdAt = NSDate()
}
class ItemList: Object {
    @objc dynamic var listName = ""
    @objc dynamic var createdAt = NSDate()
    let items = List<Item>()
}

TableView

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
               
    var allItems : Results<Item>!
    var groceryList : ItemList!
       
    override func viewDidLoad() {
        super.viewDidLoad()

        groceryList = realm.objects(ItemList.self).filter("listName = %@", "groceryList").first              
        updateResultsList()
    }

    func updateResultsList(){
        if let list = groceryList{
            allItems  = list.items.sorted(byKeyPath: "createdAt", ascending: false)
        }
    }
 
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allItems.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "reusableCell", for: indexPath) as! CustomCell
       
        let data = allItems[indexPath.row]
        
        cell.displayProductName.text = data.productName

        return cell
    }  
}

#2

You can do this by simply keeping two Results and two tableview sections. Configure cell from its proper Results depending on which section it’s in.


#3

It’s what I was thinking but I wasn’t sure if was the best way to do it since I will be deleting items from the table and dealing with two Results seemed a little trickier.

Let me give it a try.

Or maybe use three (3) different results? One to manage all items for deleting updating etc. and the other two (2) to simply hold the active/inactive items.

Thanks a lot for your help.


#4

Can you handle this in the tableView Delegate?

let data = allItems[indexPath.row]
if data.isItemActive
   put item in active section
else
  put item in inactive section