Tableview Returns nil but the Results var contains objects



I have a local database that I load Realm objects in the viewWillAppear and when I check the Results variable for .count, sure enough, the count is correct.

Yet when the tableView calls numberOfRowsInSection the same variable returns nil.

I am stumped.

Any clues where I am going wrong?



do you tableView.reloadData() after you populate the Results variable ?


Yep. I do. Thanks for the suggestion! This one is a puzzler!


edit: share your code?


Sure, here are the salient parts. Have done this code dozens of times, not sure why this is not working as expect now.

Thanks for looking.

import UIKit
import RealmSwift

class LedgerVC: UIViewController, UITableViewDataSource, UITableViewDelegate {

   @IBOutlet weak var tableView: UITableView!
	var loandata:Results<LoanData>?   
	override func viewDidLoad() {
    tableView.delegate = self
    tableView.dataSource = self
	override func viewWillAppear(_ animated: Bool) {
    	let realm = try! Realm()
    	let loandata = realm.objects(LoanData.self)

//returns .count OK here.

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return loandata != nil ? loandata!.count : 0

//returns nil here



The loandata on the viewWillAppear is an another variable, not the Result that you use in the numberOfRowsInSection. (at least from the shared code)


Hmmm, loandata is spelled the same, I even cut and pasted rather than auto-complete. If I try LoanData, I get an error that Results does not contain .count.

Will have to see what I am missing.

Thanks for looking.


that’s your problem. You have a class var defined as loandata but your loading the realm results into a local var within the viewWillAppear function.

To fix, do this

override func viewWillAppear(_ animated: Bool) {
   let realm = try! Realm()
   self.loandata = realm.objects(LoanData.self) //always refer to class vars with self.


Thank you so much! I have been chasing this problem for days!

It is stunning how that simple LET was sitting right in front of me for days and I never saw it!

You opened my eyes and I am grateful!

Thanks again!