0

So I'm looking for a good way to access all the objects of a given type from realm.

extension Object {

    static func getAll<T: Object>() -> Results<T>
    {
        let realm = try! Realm()
        let sorts = [SortDescriptor(property: "createdAt")]
        let objects = realm.objects(T).sorted(sorts)
        return objects
    }

}

Example:

class Person: Object {
    dynamic var createdAt = NSDate()
}

Then I want to call:

Person.GetAll()

The issue is that this returns "Results< T >". But I want it to return results based on the class type.. So for this case "Results< Person >". I'm assuming the T is just the generic Object.

I feel like I'm really close, just not quite there yet.

Does this make sense?

nhgrif
  • 61,578
  • 25
  • 134
  • 173
JoeBayLD
  • 939
  • 2
  • 10
  • 25
  • What you are asking for does not make sense. [Subclasses of a generic are also generic](http://stackoverflow.com/q/24138359/2792531). For more reading, perhaps check out [this answer](http://stackoverflow.com/a/27922252/2792531). – nhgrif Mar 10 '16 at 00:04
  • What if there were a protocol I added to my objects? How would I implement that so I just need to return something like "let type = Person.self" in the model class? – JoeBayLD Mar 10 '16 at 00:10

2 Answers2

0

This works only as long as you hint the compiler about what type you want to get returned, e.g.

let results: Results<Person> = Person.getAll()

But you can't define the method generically in such a way that the class you're calling it on will fill the type parameter. You would need to use Self for that purpose, but that would end up in a compiler error as:

'Self' is only available in a protocol or as the result of a method in a class; did you mean 'Object'?

marius
  • 7,766
  • 18
  • 30
-1

I don't see any problem with it. If you want to get an array of the type you're asking, just do Person.GetAll().flatMap { $0 }

J.Wang
  • 1,136
  • 6
  • 12