从另一个线程保存领域中的对象?
Save objects in realm from another thread?
当我尝试在后台保存对象时,出现异常 - "Realm accessed from incorrect thread."
这是领域的初始化 - "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];
}
来自文档:
RLMRealm instances are not thread safe and can not be shared across
threads or dispatch queues. You must call this method on each thread
you want to interact with the realm on. For dispatch queues, this
means that you must call it in each block which is dispatched, as a
queue is not guaranteed to run on a consistent thread
当我尝试在后台保存对象时,出现异常 - "Realm accessed from incorrect thread." 这是领域的初始化 - "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];
}
来自文档:
RLMRealm instances are not thread safe and can not be shared across threads or dispatch queues. You must call this method on each thread you want to interact with the realm on. For dispatch queues, this means that you must call it in each block which is dispatched, as a queue is not guaranteed to run on a consistent thread