How to use query results on main UI thread if query is done on secondary thread?

113 views
Skip to first unread message

Ios Dev

unread,
Nov 22, 2014, 4:37:18 PM11/22/14
to realm...@googlegroups.com
Supposedly Realm objects can only be used on the thread they were created on.  So if I have a potentially slow query that I run async on a secondary thread, how do I pass its data back to the main UI thread without copying it all into dictionaries or similar?

ja

unread,
Nov 23, 2014, 6:03:07 AM11/23/14
to realm...@googlegroups.com
Unfortunately cross thread object access is probably the biggest pain point in Realm at the moment and we have been discussing ways to make this easier.

So one of the best ways to handle this currently is to have a primary key on your object and to pass primary key values between threads. You can then get a copy of each object on the main thread. You can use +objectForPrimaryKey: to look up individual objects and you can use an IN query to look up an array of primary ids, i.e. [MyObject objectsWhere:"primaryId IN %@", idArray]. Note though that doing this still performs as query on the main thread but this code path has been optimized and primary keys use indexed so this should be faster than many other queries

Ios Dev

unread,
Nov 23, 2014, 4:25:35 PM11/23/14
to realm...@googlegroups.com
Thanks ja.

Do you have an intuition as to which would be faster end-to-end of the following?

A. Do the complex query on non-main thread X, get all the primary keys of the result set and pass the N primary keys back to the main UI thread.  Then redo N individual queries on the main thread by primary key lookup.
B. Do the complex query on non-main thread X, copy all the objects into dictionaries and pass the dictionaries back to the UI thread.

My thought is that B might be faster since even in A, Realm needs to read the objects twice and unmarshal them twice.  Copying should be fast especially if the strings are just immutable NSStrings since calling copy on an immutable string is really just calling "retain" (however that makes sense under ARC).

I think Realm is really awesome and I want to use it in potentially many projects, but this threading issue is something that needs to be solved for more general adoption.  :-)  I'd be happy to help - are you open to pull requests or do you need beta testers?

Anyway, thanks for your help and thanks for making Realm available for free - that's very generous of you and I certainly appreciate it and your help.

Best wishes.
Reply all
Reply to author
Forward
0 new messages