I have split my code in many small functions which sometimes are meant to be executed together inside a transaction. So I create somewhere a Realm and open a write block, and inside this block I call all my functions.
So far I have been passing the Realm instance as parameter to the functions in order to be re-used (for calls like realm.add), but I wonder if this is really necessary? Does it have any downsides to simply create a new instance of the Realm wherever it's needed? I also wonder, in case this is not a problem, if the fact that this new Realm is being used inside a transaction which was "started by" another Realm instance, if maybe this is a problem.
Finally, I also wonder if there may be any problems with the notification token used to suppress executing the notification block for updates - for this, the particular Realm instance I use, doesn't matter, right?
P.S. I'm talking only about using Realm in the same thread, I'm aware of the multi-thread limitations.
There's no harm in passing around Realm instances between your functions if you want to structure your code that way. There's also not really any appreciable overhead to opening multiple Realm instances on the same thread, since Realm Cocoa has an internal cache that it uses when vending out Realms on the same thread.
I suppose one possible argument against opening Realms repeatedly is that you must either use try!, or wrap each attempt to open a Realm in a do-catch block. In most cases, though, if you've opened a Realm successfully opening it again by creating more Realm instances cannot result in file-related errors (as long as you haven't abused Realm by moving the underlying database file).
You also shouldn't need to worry about notification tokens that weren't vended out by a specific Realm instance, or using one Realm instance within another Realm instance's write transaction; if you are indeed working on the same thread Realm should work just fine in the situations you described. (And if it doesn't, please file a bug against us!)
More generally speaking, it's better to worry about optimization only if you run into performance issues and Instruments has identified a particular operation as being a potential peformance bottleneck. In your case, I think you can choose whichever solution fits your personal preferences better.
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