Core Data & GCD: Passing the correct managed object context to custom NSManagedObjects

前端 未结 2 1598
遇见更好的自我
遇见更好的自我 2021-02-06 17:26

I get runtime errors which seem to result from my incorrect implementation of GCD in combination with my custom NSManagedObjects.

Nested in a GCD

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-06 17:48

    That error generally relates to using a managed object incorrectly context across different threads or queues. You created the MOC on the main queue, but you're using it on a background queue without considering that fact. It's not wrong to use the MOC on a background queue, but you need to be aware of that and take preparations.

    You didn't say how you're creating the MOC. I suggest that you should be doing this:

    NSManagedObjectContext *context = [[NSManagedObjectContext alloc]
        initWithConcurrencyType: NSMainQueueConcurrencyType];
    

    With main queue concurrency you can just use it normally on the main thread. When you're in your dispatch queue though, do this:

    [context performBlockAndWait:^{
        NSFetchRequest *request = [NSFetchRequest 
            fetchRequestWithEntityName:NSStringFromClass([self class])];
        NSPredicate *predicate = 
           [NSPredicate predicateWithFormat:@"coa == %@",coaStr];
        request.predicate = predicate;
        NSArray *results = [context executeFetchRequest:request error:nil];
        // ...
    }];
    

    This will ensure that the MOC's work occurs on the main thread even though you're on a background queue. (Technically what it actually means is that the MOC's work in the background will be correctly synchronized with work it does on the main queue, but the result is the same: this is the safe way to do this).

    A similar approach would be to use NSPrivateQueueConcurrencyType instead. If you do that, you'd use performBlock or performBlockAndWait everywhere for the MOC, not just on background threads.

提交回复
热议问题