MagicalRecord MR_primaryAttribute can not ensure the entity unique

I have this problem when I use the MagicalRecord “v2.3.0-beta.4”, and I think It’s a long time issue.
I did import action in save block like this:

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
     [STUser MR_importFromArray:dictionaryList inContext:localContext];
   } completion:^(BOOL contextDidSave, NSError *error) {

Let’s say the primaryAttribute of STUser is userId, I already set the ‘relatedByAttribute’ key in the model userInfo, and it works well most of the time.

But when I dig into the code I found that MagicalRecord save the import data using a temporary context:

+ (void) saveWithBlock:(void(^)(NSManagedObjectContext *localContext))block completion:(MRSaveCompletionHandler)completion;
    NSManagedObjectContext *savingContext  = [NSManagedObjectContext MR_rootSavingContext];
    NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextWithParent:savingContext];
    [localContext performBlock:^{
        [localContext MR_setWorkingName:NSStringFromSelector(_cmd)];
        if (block) {
        [localContext MR_saveWithOptions:MRSaveParentContexts completion:completion];

As I know, the import action takes time, so if I import the same data multiple times in the same moment, it will create numbers of temporary context for saving. However, MagicalRecord decides whether the entity already existing by find it using the primary key, BUT in the current context, not all contexts. The result is, we have a lot duplicate entities in our persistence dataBase.

Any suggest will be helpful.


Source: ios

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.