0

I have a Realm database which holds records for different users with distinct userID's.

I also have a UITableViewController which displays the results of a Realm query. I would like the query to return only the Passages for the current user.

class PassageListController: UITableViewController {

  var currentUserID: Int = NSUserDefaults.standardUserDefaults().objectForKey("currentUserID") as! Int
  lazy var dataArray: Results<Passage> = { return try! Realm().objects(Passage).filter("userID == \(currentUserID)")}

The problem is that I'm getting the following error message:

Instance member 'currentUserID' cannot be used on type 'PassageListController'

This is despite trying to lazily load the Realm query. What is the best practice method to solve this problem?

Anticipating some solutions:

  1. I can't load the query in viewDidAppear() as there is no way to define an empty Realm Result and it needs to be accessible throughout the controller.
  2. I could set the currentUserID as a global variable but that violates my principles.
Andy
  • 1,801
  • 3
  • 22
  • 33

2 Answers2

1

It looks like it's having some trouble working out the computed value of currentUserID before even getting to the Realm query.

Looking around on SO, it looks like this sort of issue can be solved by changing the definition of currentUserID to a read-only accessor:

var currentUserId: Int {
   get {
      return NSUserDefaults.standardUserDefaults().objectForKey("currentUserID") as! Int
   }
}

I hope that helped!

Community
  • 1
  • 1
TiM
  • 15,812
  • 4
  • 51
  • 79
0

TiM's answer clued me in to the right approach:

  class PassageListController: UITableViewController {

    var currentUserID: Int = NSUserDefaults.standardUserDefaults().objectForKey("currentUserID") as! Int

    var dataArray: Results<Passage> {
      get {
        return try! Realm().objects(Passage).filter("userID == \(currentUserID)")
      }
    }

The project builds now but I'm not sure whether this is the best approach with Realm because

  • now the query will potentially be run every time dataArray is accessed, and
  • I'm not sure whether Realm's notifications will work.
Andy
  • 1,801
  • 3
  • 22
  • 33
  • Glad I could help! Hrmm, yeah. If you're plugging that array into a table view, that seems like a really inefficient way to go. If viewDidAppear is too late, I wonder if it's worth performing this query before even transitioning to this view controller, and simply passing the results to it upon instantiation. – TiM Sep 25 '15 at 02:25