Working with objects dynamically


#1

Hi guys,

I was wondering if the following scenario is possible.

At runtime, I am able to read the schema from my Realm, here is how it looks like (the custom object create by me) :

Person {
		name {
			type = string;
			objectClassName = (null);
			linkOriginPropertyName = (null);
			indexed = NO;
			isPrimary = NO;
			array = NO;
			optional = NO;
		}
		age {
			type = int;
			objectClassName = (null);
			linkOriginPropertyName = (null);
			indexed = NO;
			isPrimary = NO;
			array = NO;
			optional = NO;
		}
	}

Would be possible to work with Realm by using this information ? Meaning all that CRUD operations.

Thanks for the help!


#2

That’s not really a schema per se, that’s an object. In this case is a Person object with two properties, name (a string) and age (an int).

It’s not a Realm object and would not be managed or stored in Realm.

A Managed Realm object would look like this

class Person: Object {
    @objc dynamic var name = ""
    @objc dynamic var age = 0
}

Are you looking to dynamically access Person properties when they are not known?

    let myPerson = Person()
    let personMirror = Mirror(reflecting: myPerson)
    for prop in personMirror.children {
        let label = prop.label
        let value = prop.value
        print(label, value) //prints the property and value of each Person property
    }

It that’s not it, can you clarify what you are asking?


#3

Thanks for the reply.

I would like, without defining the class Person to create a Person object and add it to Realm, or to update an existing one or to read one.

Basically I know what properties Person has, but only at runtime, so I can’t create the actual class in advance.


#4

Realm requires objects to be defined in order for them to be managed. There are ways around that but it goes against the grain. It seems a little odd you would want to create managed objects on the fly - those would be potentially be property-less objects with no defined structure and no real way to manage, query or work with the data.

Perhaps if you explain your use case, there may be better solutions.