Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Values without affecting stored objects - Realm swift

Tags:

ios

swift

realm

I'm using realm to save my data. My problem is that I want to have some minor, temporary changes in objects, I don't want those changes to reflect in my stored objects but realm doesn't allow me to change retrieved objects' properties without a write block, eventually leading to save my temporary changes in database. I can't make copies of objects by creating new objects and assigning values as I have big data set.

Is there any simple solution to achieve this?

like image 773
Arslan Asim Avatar asked Jun 06 '16 11:06

Arslan Asim


1 Answers

Unfortunately, as you've already stated, you can't apply new values to Realm properties 'temporarily' once the Realm Object has been written to a Realm file. This is an established fact of Realm's implementation, and there's no official way around it. As such, it'll be necessary to come up with a different mechanism to store those temporary values elsewhere, and write them to Realm when the time comes.

Something you could consider here is using Realm's ignored properties feature. Essentially, you can mark certain properties in a Realm Object to explicitly NOT get written to Realm files, and you're free to modify them anytime (and on any thread) you want.

class TestObject: Object {
  dynamic var tmpValue = ""
  dynamic var actualValue = ""

  override static func ignoredProperties() -> [String] {
    return ["tmpValue"]
  }
}

If the type of temporary data getting generated is consistently the same type each time, you can create special ignored properties in your model object to hold onto each of those properties, and then when you want to actually save them in Realm, you just copy the values from the ignored properties to the Realm properties in a write transaction.

Of course, these ignored values only persist in the instance of the Realm Object in which they were added. So if your architecture means that you're dealing with multiple Realm Object instances pointing to the same data source on disk, it might be better to separate these temporary values completely from the Realm Object and hang onto them in memory somewhere else.

Finally, while you've said you'd rather not create non-persisted copies of Realm objects because of their size, a few people have already created some pretty cool ways to perform such a copy without much code (My favourite example is in the Realm-JSON project), which still might be worth considering. Good luck!

like image 95
TiM Avatar answered Nov 16 '22 14:11

TiM