Wolf Wolf - 1 year ago 59
Swift Question

Realm: Partially update

I'm using realm in my Swift project and I'm having issues partially updating objects.

The problem is that I have an object that contains information from the server plus user generated informations. In my case it is a Topic that can be either visible or hidden by default, but the user can change the visibility value.

When I launch my app for the first time I call my server API to fetch the information to create a Topic object: it has as

. Then the user makes a choice and set the
value to

The second time that I launch the application I fetch the info again from the server and I recreate the Topic.
Then I call the Realm method
to update the object but this updates even the
property to

I know that there is another method
but this means that I have to create a big dictionary with all the values I want to update. My model objects are not so small, in some cases I have a lot of properties and the dictionary would be huge.
I don't like this approach, it is complicated to maintain.

Do you have any hint on how to handle a case like this?

A possibile way would be to create another Object (table) that has a relationship to Topic and one property
that is not overridden when I create the Topic again, but it sounds odd to create a table just for this thing.

Answer Source

This probably would be easier solved if you were passing a dictionary to create:value:update: since you could simply omit the visibility property, but as you said for size constraints, you're using a new instance of the model object that has visibility already set to a different value by the server response, then this can't really be helped. Realm cannot tell that you wish to keep this particular property and change the rest.

If you're using a primary key, then the quickest fix to this would be to simply fetch the original object via its primary key beforehand, make a note of its visibility property, and then re-set it after you've performed the update.

Breaking the visibility property off into its own object would work, but you'd most likely run into the same issue with the new object instance setting that property to nil.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download