简体   繁体   English

Swift Realm - 获取所有数据库对象的类型

[英]Swift Realm - get types of all database objects

I have a list of various objects in my Realm Database all of which are created as default ClassName: Object classes.我的 Realm 数据库中有一个各种对象的列表,所有这些对象都是作为默认类名创建的ClassName: Object类。 Is there any way to get types (classes names) of those objects, that can be saved as variables, or create an enum of these types?有没有办法获取这些对象的类型(类名),可以保存为变量,或者创建这些类型的枚举?

The issue is that Realm Results objects are homogenous - they only contain one object type.问题是 Realm Results对象是同质的 - 它们只包含一种 object 类型。 That translates to meaning you will never have a situation where Results would contain Person and Dog classes at the same time.这意味着您永远不会遇到 Results 会同时包含PersonDog类的情况。

That being said we have the option of using the Realm AnyRealmValue话虽如此,我们可以选择使用 Realm AnyRealmValue

Let me set this up: Suppose you have a PersonClass and a DogClass让我设置一下:假设你有一个 PersonClass 和一个 DogClass

let dog = DogClass()
let person = PersonClass()

and a class with a List that can contain AnyRealmValue和一个 class 和一个可以包含 AnyRealmValue 的列表

class MyClass: Object {
   @Persisted var myList = List<AnyRealmValue>()
}

when then need to cast those objects to AnyRealmValue to make this work然后需要将这些对象强制转换为 AnyRealmValue 以使其工作

let obj0: AnyRealmValue = .object(dog)
let obj1: AnyRealmValue = .object(person)

and we add those to the List我们将它们添加到列表中

let m = MyClass()
m.myList.append(obj0)
m.myList.append(obj1)

You mentioned switch but here's a simple if...then clause to handle them differently - depending on the class您提到了switch ,但这里有一个简单的 if...then 子句以不同方式处理它们 - 取决于 class

if let person = item.object(PersonClass.self) {
   print("is a person")
} else if let dog = item.object(DogClass.self) {
   print("is a dog")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM