开发者

Relationship Set disappears in Core Data with multiple contexts

开发者 https://www.devze.com 2023-04-08 16:11 出处:网络
I have an an entity A which has a to-many relationship with entity B along with the respective inverse relationship.

I have an an entity A which has a to-many relationship with entity B along with the respective inverse relationship.

I add B objects to A like this:

    NSMutableSet *bSet = [aObj mutableSetValueForKey:@"B"];
    for (bData in some array) {
        [ create and insert bObj within SAME context ];
        [bSet addObject:bOjb];
    }
    [context insertObject:aObj];

    [context save:&err];

This works fine and dandy in a one-thread situation or in a 2-thread situation using one NSManagedObjectContext across both threads (which is definitely BAD, but I was just testing).

But once I try creating the necessary second NSManagedObjectContext for the background thread that inserts the A & B objects, that relationship info doesn't seem to persist. The A and B objects are definitely there, but no relationship between them.

Here's how I create the 2nd MOC:

    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
   开发者_开发知识库 [context setPersistentStoreCoordinator:[(AppDelegate*) [UIApplication sharedApplication].delegate persistentStoreCoordinator]];

Note that I access the Core Data in the main thread, and insert them in the background thread. I've used mergeChangesFromContextDidSaveNotification in the main thread's context from a NSManagedObjectContextDidSaveNotification, but that didn't seem to do anything.

UPDATE:

It looks like this was an issue where I was releasing the MOC too early/improperly. Simply commenting out the release caused the issue to go away, but a little rewrite the memory management for the context fixed it correctly.

0

精彩评论

暂无评论...
验证码 换一张
取 消