nickheck
nickheck

Reputation: 79

Save objects in realm from another thread?

When i try save object in background, i have exception - "Realm accessed from incorrect thread." This is initialization for realm - "self.realm = [RLMRealm defaultRealm]"

My method for save object in background to realm:

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

Upvotes: 0

Views: 907

Answers (1)

bbum
bbum

Reputation: 162722

From the documentation:

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

Upvotes: 1

Related Questions