Core Data: Inverse relationship only mirrors when I edit the mutableset. Not sure why.

Posted by zorn on Stack Overflow See other posts from Stack Overflow or by zorn
Published on 2010-03-31T18:41:32Z Indexed on 2010/03/31 18:43 UTC
Read the original article Hit count: 358

Filed under:
|

My model is setup so Business has many clients, Client has one business. Inverse relationship is setup in the mom file.

I have a unit test like this:

- (void)testNewClientFromBusiness
{
    PTBusiness *business = [modelController newBusiness];
    STAssertTrue([[business clients] count] == 0, @"is actually %d", [[business clients] count]);
    PTClient *client = [business newClient];
    STAssertTrue([business isEqual:[client business]], nil);
    STAssertTrue([[business clients] count] == 1, @"is actually %d", [[business clients] count]);
}

I implement -newClient inside of PTBusiness like this:

- (PTClient *)newClient
{
    PTClient *client = [NSEntityDescription insertNewObjectForEntityForName:@"Client" inManagedObjectContext:[self managedObjectContext]];
    [client setBusiness:self];
    [client updateLocalDefaultsBasedOnBusiness];
    return client;
}

The test fails because [[business clients] count] is still 0 after -newClient is called.

If I impliment it like this:

- (PTClient *)newClient
{
    PTClient *client = [NSEntityDescription insertNewObjectForEntityForName:@"Client" inManagedObjectContext:[self managedObjectContext]];
    NSMutableSet *group = [self mutableSetValueForKey:@"clients"];
    [group addObject:client];
    [client updateLocalDefaultsBasedOnBusiness];
    return client;
}

The tests passes.

My question(s): So am I right in thinking the inverse relationship is only updated when I interact with the mutable set? That seems to go against some other Core Data docs I've read. Is the fact that this is running in a unit test without a run loop have anything to do with it?

Any other troubleshooting recommendations? I'd really like to figure out why I can't set up the relationship at the client end.

© Stack Overflow or respective owner

Related posts about cocoa

Related posts about core-data