TimSim
TimSim

Reputation: 4036

Realm Results object type

This is really basic but I just can't find how to get all objects of a type from a Realm database using Swift. Yes, yes:

var dogs = try! Realm().objects(Dog)

but what if I want to declare and initialize the dogs variable beforehand and load objects into it later? Like:

var dogs = ???
dogs = realm.objects(Dog)

What should the type of variable dogs be in this case?

Upvotes: 2

Views: 6393

Answers (2)

Michael Moulsdale
Michael Moulsdale

Reputation: 1488

As well as Results you can also use List. This is useful if you are returning objects in a One:Many example.

In the case where you have two models Country and City, where a Country can have many cities.

var rlmCountry: Country!
var rlmCities: List<City>?

rlmCities = rlmCountry.cities

Upvotes: -2

bdash
bdash

Reputation: 18308

Realm.objects(_:) has the following signature:

public func objects<T: Object>(type: T.Type) -> Results<T>

The signature tells you that when you call the function as realm.objects(Dog), the return type will be Results<Dog>.

If you wish to declare the variable and initialize it later in the same function, you can simply separate the declaration from the initialization, like so:

let dogs: Results<Dog>

// …

dogs = realm.objects(Dog)

If you are declaring a member variable and need to initialize it after init, you should declare as an optional and using var:

var dogs: Results<Dog>?

// …

dogs = realm.objects(Dog)

Upvotes: 7

Related Questions