Question

So I have no idea why I am getting this error. The error message is as follows:

* Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on a RLMRealm instance first.' * First throw call stack: (0x2f7b0f83 0x39f61ccf 0xc46ef 0xc3c23 0xc0c9d 0xb3e73 0x3a449833 0x3a449ded 0x3a44a297 0x3a45c88d 0x3a45cb21 0x3a58bbd3 0x3a58ba98) libc++abi.dylib: terminating with uncaught exception of type NSException

And is thrown while executing this code.

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UITextField * alertTextField = [alertView textFieldAtIndex:0];
    if (![self.chatSession.theirAlias isEqualToString:alertTextField.text]) {
        self.sender = alertTextField.text;
        dispatch_queue_t queue = ((AppDelegate *)[UIApplication sharedApplication].delegate).queueForWrites;
        dispatch_async(queue, ^{
            [[RLMRealm defaultRealm] beginWriteTransaction];
            self.chatSession.myAlias = alertTextField.text; // This is the line where the error is thrown
            [[RLMRealm defaultRealm] commitWriteTransaction];
        });
    } else {
        [self promptForAliasAfterRejection];
    }
}

It's pretty clear that I am writing inside of a write transaction. Is this a bug with Realm? Or am I missing something...?

Was it helpful?

Solution

The beginWriteTransaction and commitWriteTransaction have to be called on the same realm the object you're modifying is in. Each time you call [RLMRealm defaultRealm], you're getting a new realm. This is not going to be the same realm that's in self.chatSession. To fix this, first confirm that self.chatSession's realm is on the same queue as your queueForWrites (I'm assuming self.chatSession is a RLMObject, of course). Then, just do the following inside the block instead:

[self.chatSession.realm beginWriteTransaction];
self.chatSession.myAlias = alertTextField.text;
[self.chatSession.realm commitWriteTransaction];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top