试图在写入事务之外修改对象

时间:2014-07-31 05:44:09

标签: ios uialertview realm

所以我不知道为什么我会收到这个错误。错误消息如下:

*由于未捕获的异常'RLMException'而终止应用程序,原因是:'尝试修改写事务之外的对象 - 首先在RLMRealm实例上调用beginWriteTransaction。' * 第一次抛出调用堆栈: (0x2f7b0f83 0x39f61ccf 0xc46ef 0xc3c23 0xc0c9d 0xb3e73 0x3a449833 0x3a449ded 0x3a44a297 0x3a45c88d 0x3a45cb21 0x3a58bbd3 0x3a58ba98) libc ++ abi.dylib:以NSException类型的未捕获异常终止

执行此代码时抛出。

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

我很清楚我在写一个事务中写作。这是Realm的错误吗?或者我错过了什么......?

1 个答案:

答案 0 :(得分:15)

必须在您正在修改的对象的同一领域中调用beginWriteTransactioncommitWriteTransaction。每次调用[RLMRealm defaultRealm]时,您都会获得新的领域。这不会是self.chatSession中的那个领域。要解决此问题,请先确认self.chatSession的域与queueForWrites位于同一个队列中(当然,我假设self.chatSessionRLMObject)。然后,只需在块内执行以下操作:

[self.chatSession.realm beginWriteTransaction];
self.chatSession.myAlias = alertTextField.text;
[self.chatSession.realm commitWriteTransaction];
相关问题