ios - 尝试在写入事务之外修改对象

标签 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 的错误吗?还是我遗漏了什么...?

最佳答案

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

[self.chatSession.realm beginWriteTransaction];
self.chatSession.myAlias = alertTextField.text;
[self.chatSession.realm commitWriteTransaction];

关于ios - 尝试在写入事务之外修改对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25051577/

相关文章:

iphone - 如何将 userInfo 添加到 UIAlertView?

ios - 不要关闭 UIAlertController

ios - 如何使用 Realm 存储字符串枚举

realm - 从本地切换到同步 Realm

ios - 我应该在 Swift 中使用单例位置管理器吗?

ios - iPhone 应用程序崩溃加载 View

ios - 如何使用自动布局避免 UITextField 和键盘之间的冲突?

ios - 如何在 UIAlertController 中设置两个 UITextField 之间的距离?

android - 有没有办法在 Android 上隐藏/混淆 .realm 文件?

ios - 如何在Parse iOS中避免数据重复?