当我在后台尝试保存对象时,我有异常 - “从不正确的线程访问域”。 这是领域的初始化 - “self.realm = [RLMRealm defaultRealm]”
我在背景中保存对象的方法:
- (IBAction)saveProduct:(id)sender {
Product *product = [Product new];
[self.productService addProduct:product onSuccess:^{
NSLog(@"Succes");
} onFailure:^(NSError *error) {
NSLog(@"Error");
}];
}
- (void)addProduct:(NSObject *)order onSuccess:(success)success onFailure:(failure)failure
{
__weak __typeof(self)weakSelf = self;
dispatch_async(self.queue, ^{
__strong __typeof(weakSelf) strongSelf = weakSelf;
[strongSelf.dao saveProduct:order];
dispatch_async(strongSelf.mainQueue, ^{
success();
});
});
}
- (void)saveProduct:(NSObject *)product
{
ProductModel *model = [self ponsoToModel:product];
[self.dataBase saveObject:model];
}
- (void)saveObject:(RLMObject *)object
{
[self.realm beginWriteTransaction];
[self.realm addObject:object];
[self.realm commitWriteTransaction];
[self dataBaseDidSave];
}
答案 0 :(得分:1)
来自文档:
RLMRealm实例不是线程安全的,无法共享 线程或调度队列。您必须在每个线程上调用此方法 你想与领域互动。对于调度队列,这个 意味着你必须在调度的每个块中调用它,作为a 不保证队列在一致的线程上运行