Let's have this example:
We work with a set of animals. Let's assume that we don't need all animals persisted in the database, and there is a logic that controls adding and removing animals from database.
For example I have an object, a Horse, with string property name
with "Suey", and I add her to Realm, with addObject:
.
So now we have this object saved to Realm. This object is valid, and we can do horse.name
, which will return "Suey".
What happens next is that I need to remove Suey from DB. I do deleteObject:
. But sadly, it removes not only the persisted info about the horse, but also made my object invalid. Suey is basically dead, so if I want her back in the DB I need to create another horse from ground up, and only after that I will be able to have another Suey in the DB.
Is there another way of keeping Suey alive, so I have more flexibility on managing her state?
I hope I made the point clear, please let me know if you have any questions.
Thanks in advance!
UPDATE
The Horse IS engaged in one-to-many relationship, so it's life span also impacts properties in related models.
Objects in Realm are accessors for the equivalent object int the database. If for whatever reason, you need to "detach" the object variable from its on-disk representation, you can copy it into memory. An easy way to do that is to create a new, un-persisted object with the contents of the persisted one:
// Assuming `Horse` inherits from `RLMObject` and `persistedHorse` is attached to an `RLMRealm`.
Horse *persistedHorse = ...;
Horse *inMemoryHorseCopy = [[Horse alloc] initWithObject:persistedHorse];
// This will create a new `Horse` object, not tied to an RLMRealm,
// by copying the contents of `persistedHorse`.
You can use the same approach whenever you need to copy an existing RLMObject
either into a stand-alone object (as above), or into another realm.
According to the documentation every modification of your query result object (in your case Object Horse with Name Suey) modifies the data on disk directly because the result is the actual data and not a copy of it. So if you remove the horse you have to create a new one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With