Can't delete Realm database objects from another thread (even after searching)

巧了我就是萌 提交于 2019-12-13 05:05:44

问题


I'm having a similar problem as the poster in this thread: Unable to delete an object in a realm database

I have an array of RLMObject subclasses created from a search on a queue called 'syncQueue'. It's a bunch of Diagnostic objects that need to be sent up to the server.

These objects are packaged up and sent up to the server using the Google Client Library for iOS. Once the library returns that the objects have been successfully uploaded, I want to delete them out of Realm. I grab some samples out of Realm.

NSArray *samples = [someClass getMySamplesFromRealm];

So now I have an array of samples. ^^This happens on the 'syncQueue', which uses its own thread. Still on the same thread, we package and upload the samples. So there's a callback block that looks something like this:

GTLServiceTicket *ticket = [service executeQuery:query completionHandler:^(GTLServiceTicket *ticket, id object, NSError *error)
    {
        [syncHandler removeTicket:ticket];
        if( error )
        {
            // Handle Error
        }
        else
        {
            [diagDataAccessManager deleteObjects:samples];
        }
    }];

Here is the code that deletes these objects.

1  - (void)deleteObjects:(NSArray *)samples
2  {
3      if (samples.count > 0) 
4      {
5          [[RLMRealm defaultRealm] beginWriteTransaction];
6          for (Diagnostic *diagnostic in samples) 
7          {
8              Diagnostic *diagnosticToDelete = [Diagnostic objectForPrimaryKey:diagnostic.primaryId];
9              [[RLMRealm defaultRealm] deleteObject:diagnosticToDelete];
10         }
11         [[RLMRealm defaultRealm] commitWriteTransaction];
12     }
13     
14 }

So I'm trying to do a search before I do a delete. However...

On line 8, I get an exception: "Realm accessed from incorrect thread" Now, I assume this is because when I run Diagnostic objectForPrimaryKey:, it's trying to use the Realm associated with the *diagnostic object, which was created on another thread.

My question is: how on Earth can I delete these specific objects, if I can't look at them to figure out which specific objects they are?

Any clarification/advice would be much appreciated.


回答1:


Your best will probably be to pass the primary keys to the new thread, rather than the objects.



来源:https://stackoverflow.com/questions/29423859/cant-delete-realm-database-objects-from-another-thread-even-after-searching

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!