Search code examples
swiftswift3realm

Realm created_at & updated_at timestamps


I want to implement 2 timestamps into my Realm objects created_at and updated_at.

created_at would only ever be set once when the object is first inserted into the database.

updated_at would store a new timestamp each time the object is modified and saved.

The only way i've found I could do this, is too use the Repository Pattern, with a create and update function, which would then set the timestamps. However adopting this pattern means refactoring quite a lot of code.

From what I can tell Realm objects do not have any sort of hooks such as beforeSave & afterSave that I could implement on the object models themselves, which would have been a useful alternative.

Apart from the repository pattern, or manually updating the timestamps before any realm.write's throughout my application, are there any other ways that I could accomplish this?


Solution

  • You have two methods provided by Realm to achieve what you are looking for.

    The first method is Key-Value Observation, which implements a widely used design pattern with the same name. See Apple's documentation on the topic.

    The second method is Realms own alternative, called Notifications. You can get notifications about each write transaction to a specific Realm instance and handle the ones you need to handle or you can register for notifications about single Objects.

    You can use both methods to update the updated_at property of your Realm objects when you observe/get notified about an update to your object. Handling the created_at property is even easier, you just have to set it up to an immutable value at the initialization of your object or you can even do it automatically inside the objects initializer function.