Tableview Returns nil but the Results var contains objects


#1

Hi,

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?

Thanks!!
Blessings,
—Mark


#2

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


#3

Yep. I do. Thanks for the suggestion! This one is a puzzler!
Blessings,
—Mark


#4

edit: share your code?


#5

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() {
    super.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.
tableView.reloadData()
}

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

//returns nil here
}

}


#6

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


#7

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.
Blessings,
—Mark


#8

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.
   self.tableView.reloadData()
}

#9

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!

Blessings,
—Mark