magicalpanda / MagicalRecord

Super Awesome Easy Fetching for Core Data!
Other
10.8k stars 1.79k forks source link

Mutiple MR_find in the same method cause concurrency problem #1165

Open engmsaleh opened 8 years ago

engmsaleh commented 8 years ago

I have a method where I need to do two consecutive MR_find and I'm using MR 2.3. Currently I'm using the CoreData concurrency debug and I always get a concurrency problem with the second MR_find Here is the method under investigation:

-(NSArray*)fetchParticipantsListForSessions:(NSArray *)sessions{

    for (EventSession* session in sessions) {
        NSPredicate *sessionPredicate= [NSPredicate predicateWithFormat:@"eventSessionID == %@ AND eventSpeaker == 1 AND eventParticipantSessionIsDeleted == 0",[session eventSessionID]];
        NSArray* eventParticipantSessionsManaged =[EventParticipantSessionManaged MR_findAllWithPredicate:sessionPredicate];

        NSMutableArray* eventSessionSpeakers = [[NSMutableArray alloc] init];

        for (EventParticipantSessionManaged* eventParticipantSessionManaged in eventParticipantSessionsManaged) {

            EventParticipantManaged * eventParticipantManaged = [EventParticipantManaged MR_findFirstByAttribute:@"eventParticipantID" withValue:[eventParticipantSessionManaged eventParticipantID]];

            NSError *error = nil;
            EventParticipant * eventParticipant = [MTLManagedObjectAdapter modelOfClass:EventParticipant.class
                                                              fromManagedObject:eventParticipantManaged
                                                                          error:&error];
            if (eventParticipant) {
                [eventSessionSpeakers addObject:eventParticipant];
            }
        }
        [session setEventSessionSpeakers:eventSessionSpeakers];
    }

    return sessions;
}

I think it is maybe due to accessing data from multiple contexts , but I'm not sure. As I dig through MR_find and as I can see that they are using the current thread and as I understand it is MainContext , Please tell me if I'm wrong? Also, I see that all methods that don't specify a context is deprecated if so , Could you advise about the correct way of doing such manipulation?

tonyarnold commented 8 years ago

You should have a read of @casademora's article Why contextForCurrentThread Doesn't Work in MagicalRecord for an explanation of what I think is happening here.

Also, I see that all methods that don't specify a context is deprecated if so , Could you advise about the correct way of doing such manipulation?

You need to use the method that requires you to specify a context, and create one using [NSManagedObjectContext MR_context] (or use one you already have on hand, but be aware of Core Data's threading rules).