Wolf Wolf - 20 days ago 5
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

visibility
value
undefined
. Then the user makes a choice and set the
visibility
value to
visible
.

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
add:update:
to update the object but this updates even the
visibility
property to
undefined
again.

I know that there is another method
create:value:update:
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
visibility
that is not overridden when I create the Topic again, but it sounds odd to create a table just for this thing.

TiM TiM
Answer

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.