Search code examples
iosswiftrealm

Trying to backtrace an uncaught exception 'RLMException', reason ... may only be called on RLMArray


I'm having trouble tracking down the source of one of these errors:

*** Terminating app due to uncaught exception 'RLMException', reason: 'This method may only be called on RLMArray instances retrieved from an RLMRealm'

I know that it is most likely I am calling a filter() or a sorted() function on an Object instance that has not been stored in a realm properly. To make things worse, my app works perfectly okay when run in the simulator, but it doesn't when I run it on my iPhone, so thread timing is probably at play.

As I am using Swift, it is hard to trap and backtrace the Exception. Are there any tricks you can suggest other than stepping through every step until I find where it is happening?


Solution

  • Okay, so I found the problem, but it is interesting how it ends up being reported.

    The cause of the fault is that part of my code was attempting to add a notification block to a List<> within an Object that was in the process of being committed to its realm. To overcome this fault, I make sure the commit happens first, then the notification block is added second: life is good again. It is interesting that it only shows up when run on an actual device and not in the simulator, but such are the vagaries of simulators.

    Perhaps it would be helpful for realm.io to look at a precondition for addNotificationBlock regarding this fault and throw a more meaningful error that makes it easier for programmers to trap and resolve.