Realm Results object type

爷,独闯天下 提交于 2019-12-10 23:56:22

问题


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?


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/36486167/realm-results-object-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!