Attempting to Modify Object Outside of Write Transaction

拈花ヽ惹草 提交于 2019-12-04 19:05:25

问题


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...?


回答1:


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];


来源:https://stackoverflow.com/questions/25051577/attempting-to-modify-object-outside-of-write-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!