How to customize getter & setter in Realm Swift?

1.5k Views Asked by At

I'm new to Realm, I used to use MagicalRecord before.

In MagicalRecord, I can handle import function or even set some mappingKeys for multiple candidate names.

I would like to customize some of the properties of my Realm object.

I found DynamicObject that looks like what I want. However, I have no idea how to use it.

1

There are 1 best solutions below

0
marius On

To customize your getters and setters with Realm Swift, you will need to define a plain underlying stored property. You can then access this property from another you define on top of that with custom setters and getters as seen below.

public class Foo : Object {
    private dynamic var _bar: Int

    public var bar: Int {
        get {
            return _bar + 1
        }
        set {
            _bar = newValue - 1
        }
    }
}

Note that using Swift's willSet or didSet with Realm Swift might not work like you expect. They are only triggered for unattached standalone objects. Once you persist an object or retrieve a persisted obejct, all getters and setters are overridden to directly access the persisted values.


DynamicObject is not what you want to use. This is intended for use-cases, where you don't have strong guarantees over your object schema and need to deal with either unstructured data or databases you didn't created yourself.