Realm accessible from the wrong thread while saving an object

I am using Realm for a messaging app. I need to change some of the requested objects, for example if the object is a multimedia message that doesn't have a thumbnail yet. Then I will load it and try to store it in an object.

I could run multiple downloads at the same time as it happens inside the for loop. Why would it be throwing this exception when I assign a new instance of my Realm Realm to each save object?

I tried wrap the load block in dispatch_async

, thinking it might be a race condition or something related, but no luck, it still throws an exception.

'RLMException', reason: 'Realm accessed from incorrect thread'

RLMResults *messages = [[Message objectsWhere:@"jabberID = %@", self.recipientJID] sortedResultsUsingProperty:@"date" ascending:YES];

for (Message *message in messages) {
  if (!message.hasThumbData) {

    [self downloadMedia:message.remoteMediaURL success:^(NSData *mediaData) {

      RLMRealm *realm = [RLMRealm defaultRealm];
      [realm beginWriteTransaction];
      message.hasThumbData = YES;
      message.thumbData = mediaData;
      [realm commitWriteTransaction]; 

    } failure:^(NSError *error) {
      NSLog(@"Error downloading media: %@", error.description);
    }];

  }
} 

      

+3


source to share


1 answer


Persisted Realm objects can only be read or written on the same stream on which they were retrieved. Assuming the success block [self downloadMedia:success:failure:]

is called on a different thread than messages

that, that means you can't use message

inside the block. Creating a new instance RLMRealm

for the current thread does not affect captured variables.



+2


source







All Articles