简体   繁体   中英

iOS app getting crash when adding object in RLMArray on async thread

Here is the description of Realm object :- I have one object SLRProduct which is RLMObject subclass. It holds one property comments which is RLMArray of SLRComment. SLRComment is also RLMObject subclass.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    RLMRealm *slRealm = [RLMRealm defaultRealm];
    [slRealm beginWriteTransaction];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"identifier = %@", productId];
    SLRProduct *product = [[SLRProduct objectsWithPredicate:pred] firstObject];
    [product.comments addObject:comment]; //<=== Getting crash here
    [slRealm commitWriteTransaction];
});

In this method i am adding one more SLRComment in RLMArray. When i am doing this transaction on async thread it's getting crash with exception 'Object is already persisted in a Realm' . It's working fine on main thread. Somehow i need to do this on async thread.

I had some similar problem to yours, I was trying to update some the fields of a RLMObject on a async thread.

I think that the crash isn't strictly related to the access to the NSArray, but to the attempt to modify the object itself. When you retrieve an instance of SLRProduct from a RLMRealm, this one handles the concurrency of the cancel/modify operations, since all the instances you get of the same object (eg with the same primary key) are effectively the same object. If you get it from two different slRealm, and you are using two different RLMRealms since you get them from two different threads, the app will crash because they can't handle the accesses.

I resolved my problem using the main queue ( dispatch_get_main_queue() ).

I hope this can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM