Search code examples
swiftuitableviewrealm

Why is only one of my objects in my Realm Database showing up on my tableView?


if realm.objects(Accomp2.self).count > 0 {
            for acc in accompData {
                models.removeAll()
                if acc.month == date4 {
                    models.append(acc)
                    //print(models)
                    count += 1
                }
            }
        }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = models[indexPath.row].title
        let date = models[indexPath.row].date
        let formatter = DateFormatter()
        formatter.dateFormat = "MMM dd, YYYY"
        cell.detailTextLabel?.text = formatter.string(from: date!)
        return cell
    }

In the first block of code, I add the objects that have the date from this month from the Realm Database to an array called models. When I print out models, I can see all the objects and their properties. Then, in these two tableView functions, I return the number of objects in models, but the count only returns "1." I tried to use the count variable and return that instead, but it then gives me an error in the cellForRowAt function saying that those objects do not exist. I am not sure why I can only access one of the objects from models which I declare before the viewDidLoad() method as var models = [Accomp2]() Should I be using another tableView method, or is there a way to access all of the objects and create tableView cells for all of them?


Solution

  • As of the removeAll clears the array every cycle leaving only the last item , you see all in console as you print them individually

      for acc in accompData {
                models.removeAll()
    

    i guess it could be

     models.removeAll()
      for acc in accompData {