1

After trying out AFIncrementalStore I've decided to do most of the work manually to have more control over what happens and when.

Object structure I have looks like this. "products" relationship is an ordered one.

enter image description here

Here's the code that runs inside a NSOperation

NSManagedObjectContext* childContext = [[NSManagedObjectContext alloc] initWithConcurrencyType: NSPrivateQueueConcurrencyType];
childContext.parentContext = self.parentManagedObjectContext;
[childContext performBlockAndWait: ^
{
    DashboardViewModel* dashboardViewModel = [NSEntityDescription insertNewObjectForEntityForName: @"DashboardViewModel"
                                                                           inManagedObjectContext: childContext];
    NSMutableOrderedSet* products = [NSMutableOrderedSet orderedSetWithCapacity: productRepresentations.count];
    for (NSDictionary* rawProductRepresentation in productRepresentations)
    {
        Product* product = [NSEntityDescription insertNewObjectForEntityForName: @"Product"
                                                         inManagedObjectContext: childContext];
        product.dashboardViewModel = dashboardViewModel;
        [products addObject: product];
    }

    dashboardViewModel.products = products;


    NSError* saveError = nil;
    if (![childContext save: &saveError])
        NSLog(@"Error: %@", saveError);

    //Save parent context to push changes to persistent store
    [self.parentManagedObjectContext performBlock: ^
    {
        NSError* saveParentError = nil;
        if (![childContext.parentContext save: &saveParentError])
            NSLog(@"Error: %@", saveParentError);
    }];
}];

Seems correct to me but I always get an error when saving parent context that says "Dangling reference to an invalid object.”</p>

Any suggestions?

4

1 回答 1

0

你不应该设置关系的双方。核心数据为您设置了关系的反半部分,因此您可以删除您的productsset 并仅依赖 setting product.dashboardViewModel = dashboardViewModel

于 2013-08-29T19:49:43.750 回答