1

We're finding that our project has lots of duplicated/boilerplate code surrounding collections of realm objects for basic list view controllers, and wondering if there's some generic container we can encapsulate them in.

It seems like AnyRealmCollection is vaguely related to that concept, and I found this old/spuriously sourced link and this stackoverflow post in which it does basically exactly what I want, but that syntax definitely doesn't work anymore. My goal is basically the following (pardon my pseudocode)

class ParentController: UITableViewController {
  var dataSource: GenericRealmCollection!
  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataSource.count
  }
}

class ChildController: ParentController {
  func viewDidLoad() {
    dataSource = realm.objects(MyModel.self).filter(...)
  }
}

I'm guessing there's some swift type-erasure thing that i'm not fully understanding that will accommodate this, but I've been playing around with it most of the afternoon and haven't made much progress.

Update 1

Looks like AnyRealmCollection definitely isn't what i'm looking forward based on @kishikawa-katsumi's explanation. As I mentioned in the comments, doing that forces class generics, which really limit interoperability with Obj-C. My hope is to completely erase the type (or at least get back to Object, then have helper functions for casting to the right type when I need the objects. It's looking like this may not be possible.

Community
  • 1
  • 1
Sam
  • 1,504
  • 2
  • 13
  • 19

1 Answers1

0

AnyRealmCollection<T> is used in the following manner.

class ParentController<T: Object>: UITableViewController {
    var dataSource: AnyRealmCollection<T>!
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
}

class ChildController: ParentController<MyModel> {
    override func viewDidLoad() {
        super.viewDidLoad()
        dataSource = AnyRealmCollection(realm.objects(MyModel.self))
    }
}
kishikawa katsumi
  • 10,418
  • 1
  • 41
  • 53
  • Ah, bummer, that doesn't accomplish what I'm hoping to do. I could do the same thing with Results, but that forces me to use generic classes, which really hurts interop with obj-c. Cant do nice things like `extension ChildViewController: UITableViewDataSource { }` – Sam Oct 05 '16 at 16:17