Reputation: 10194
I have a model some instances of which I need to persist. Only some, not all, since persisting all instances would be wasteful. The model has primaryKey
of type Int
I need to be able to pass all objects from background to main thread since Realm objects can only be used by the thread on which they were created. Current version of Realm Swift (0.94) does not seem to support handing the object over to another thread directly.
For persisted objects (the ones saved to storage with write
) this is not a problem, I can fetch the object on another thread by primaryKey
.
Unpersisted objects, however, are problematic. When I create a new object with the same primaryKey
in background (I suppose it should be treated as the same object since it has the same primaryKey
) and try to fetch it on the main thread (without persisting changes with write
since I don't want in in the storage), I seem to get the old object.
I see the following solutions to this problem:
1) persist all objects (which is undesirable and otherwise unnecessary)
2) keep separate model for the objects I want to persist (leads to code duplication).
3) use init(value: AnyObject)
initializer which creates unpersisted object from a Dictionary<String, AnyObject>
(would probably require manual copying of object properties to dictionary, tedious and potentially error-prone)
Are there any better solutions?
Offtopic: I haven't tried Realm for Android, is situation any better with it?
Upvotes: 5
Views: 1093
Reputation: 4120
You are free to pass unpersisted objects between threads as you wish -- only persisted objects cannot yet be handed over between different threads.
Upvotes: 6
Reputation: 80265
I think your problem is that you are creating two objects that you want to be the same object and there is no way the system can know which one you want.
The solution is as simple as it is generic: create a new object only after checking that its unique attribute does not exist already. This should work equally well with persistent and non persistent objects. Obviously, you need to have a central, thread safe in-memory repository where you can go and create new objects.
You write:
I seem to get the old object.
There should not be any old object if you have checked before.
Upvotes: 0