smileham smileham - 5 months ago 21
iOS Question

Realm.io RLMException on commitWriteTransaction - Index out of bounds

I've been using the following code successfully, and all of a sudden, for one of my models, Realm throws an index out of bounds error on

commitWriteTransaction
. The Realm objects are successfully created, and it's only on the final line below that the error appears, and it only happens for one of my models. I did update the server return recently, but the model still appears correct as it successfully creates an object from the server data (model shown below).

Btw I need to delete and reinstall the app every time it crashes. If I try to open it again, it'll crash before getting anywhere (I'm assuming that's because the DB is messed up).

What's going on? And how do I fix this?

Code:

NSDictionary *responseDictionary = (NSDictionary *)responseObject; //response from AFNetworking call to my server
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
for (NSDictionary *dict in responseDictionary){
MyModel *object = [[class alloc] initMyModelWithDictionary:dict]; //class is known
// (print object) - see output below
[realm addOrUpdateObject:object];
}
[realm commitWriteTransaction]; // Error thrown here


Model printout example (one of the ones from
dict
)


MyModel {
id = 32;
created_at = 2016-07-02 03:39:15 +0000;
updated_at = 2016-07-02 03:39:15 +0000;
intA = 1;
intB = 2;
intC = 0;
boolA = 1;
boolB = 1;
boolC = 1;
boolD = 0;
}


Error:

Terminating app due to uncaught exception 'RLMException',
reason: 'Index 0 is out of bounds (must be less than 0)'

Answer

This exception is only thrown when either a RLMArray, RLMLinkingObjects, or RLMResults has an out-of-bounds access. Given that index 0 is out of bounds, it must be empty when the 0th index is accessed. Realm isn't itself accessing this collection when you call commitWriteTransaction. Instead, it is delivering a notification to your code that is performing the out-of-bounds access. You should be able to easily find out where this is occurring by turning on exception breakpoints.

Comments