PDA

View Full Version : relationship predicate




MrFusion
Jul 6, 2006, 06:45 AM
What is missing? I think I do everything according to the manual.
Say I have entity A en B with a relationship REL (to many) from A to B but without an inverse one. B has a bool value of selected.
The user can select any B for each A and when this happens I observe the
NSManagedObjectContextObjectsDidChangeNotification
and do some stuff I want to do. For this I need all the A's that has at least one selected B.

My solution to this is:

- (NSArray *) filterDatabase:(NSPredicate *) myPredicate forEntity:(NSString *)myEntity
{
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:myEntity
inManagedObjectContext:context];
[request setEntity:entity];
[request setPredicate:myPredicate];
NSError *error = nil;
NSArray *array = [context executeFetchRequest:request error:&error];
if (error)
NSLog(@"%@",error);
return array;
}

================

NSPredicate *selRec = [NSPredicate predicateWithFormat:@"ANY REL.selected == 1"];
NSArray *result = [self filterDatabase:selRec
forEntity:@"A"];
NSLog(@"r %i",[result count]);

NSPredicate *selRec3 = [NSPredicate predicateWithFormat:@"selected == 1"];
NSArray *result3 = [self filterDatabase:selRec3
forEntity:@"B"];
NSLog(@"r3 %i",[result3 count]);

Every time something is selected, result3 is updated (as I can see with the NSLog), but the first 'result' doesn't give the right answer.

So, besides it being spaghetticode, what's wrong with it?

Thanks



MrFusion
Jul 6, 2006, 04:53 PM
The code above was right it seems and gave the correct answers. What was displayed was incorrect. When I load the database all instances of B are displayed at first until the selection of instance A is changed.
arraycontroller 1 is bound to A, and arraycontroller 2 is bound to the selection of A for the relationship from A to B.