Swift didSet and willSet on properties in Realm doesn’t work?

Are you trying to use didSet and willSet on properties created on realm based classes? Is it working? I think it won’t. If so, you have come to right place. Follow my instruction and you will be able to get what you are looking for.

Actually, willSet and didSet only works on an RLMObject before it is added to a realm. This is indeed the way it is because of the features required by Realm to provide us to maintain powerful database structure.

So, show can it be done? Well, I would recommend using a private persisted property which has no logic, along with a non-persisted computed property which has the willSet/didSet functionality. Here is an example.

class Category : Object {
    @objc dynamic var updatedAt = Date()
    @objc dynamic internal var _isDeleted = false
     var isDeleted: Bool {
         get {return _isDeleted}
         set {
             // do willSet stuff
             _isDeleted = newValue
             // do didSet stuff. for example.
             self.updatedAt = Date()
         }
     }

    override class func ignoredProperties() -> [String] {
         return ["isDeleted"]
     }
}

This way you can use willSet and didSet method easily. It will increase your code but this will work like charm.

I hope this was helpful to you. If so don’t forget to share and you can even like this post. Don’t forget that guys and girl 😉. Let me know if have any problem on this topic.

Thanks

0

Leave a Reply

santoshm