Environment: Version 7.0 beta 6 (7A192o), Realm and RealmSwift from branch swift-2.0.
I have a problem with reading data from Realm database when using background threads (NSThread or dispatch_async). For example, I create background thread A during application startup which lives during whole application life-cycle (or for some long time). When I create Realm object in thread A then I can read current data from Realm. But when I add new data to Realm from thread B then I am not able to read them in thread A. I always fetch old data. It does not matter if I use in thread A the same Realm object or create new one. It seems that once created Realm object in background thread causes that all Realm objects from this thread hold database snapshot corresponding to the database state when the first Realm object was created. To workaround this problem I need to create new thread with new Realm object and with this configuration I can read latest data from Realm.
If your thread doesn't have a running runloop, you'll need to manually refresh the Realm for it to see new data -- autorefresh happens on a spin of the runloop.
Thanks for the quick response.
Problem with missing runloop. Just as I thought after deeper debugging of Realm code.
I did manual refresh in my code and it works perfectly. My problem is fixed.
One more thing. It is clear for me that when autorefresh was not performed then existing Realm object does not have fresh data. But can you explain me why creating new Realm object does not fetch fresh data and it still points to the old one?
Realm objects are actually cached per-thread for performance (it turns out that open() is pretty expensive!), so you're getting the cached instance.
Now everything is clear. Thanks.