Sunday, 18 August 2013

Set 2 NSPredicates on a NSFetchRequest

Set 2 NSPredicates on a NSFetchRequest

I'm using Core Data and have a to-many relationship with the following
entities:
Athlete(evals)<-->>Eval(whosEval)
It starts with a table view that lists ALL athletes in the database. Then
when you select an Athlete it pulls up their Evals in a table view. The
problem is the way I am doing this is through checking their full name.
Unfortunately, it is possible for 2 athletes to have the same name. For
this reason, I check their parent's name as well, but I think I am doing
it incorrectly. Can anyone explain why the following doesn't work and how
I should do it correctly? What happens with this code is if 2 Athletes
have the same name, they'll share results. Even if their Parent's Name is
different.
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
_managedObjectContext = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSFetchRequest *athleteRequest = [[NSFetchRequest alloc] init];
[athleteRequest setEntity:[NSEntityDescription
entityForName:@"Athlete"
inManagedObjectContext:_managedObjectContext]];
NSError *athleteError = nil;
NSPredicate *athletePredicate = [NSPredicate
predicateWithFormat:@"full == %@", _athletesFullName];
[athleteRequest setPredicate:athletePredicate];
NSArray *results = [_managedObjectContext
executeFetchRequest:athleteRequest error:&athleteError];
if([results count] >1){
NSPredicate *athletePredicate = [NSPredicate
predicateWithFormat:@"pfull == %@", _athletesParentsFullName];
[athleteRequest setPredicate:athletePredicate];
}
Athlete *athleteSelected;
if([results count] >0){
Athlete *currentAthlete = [results objectAtIndex:0];
athleteSelected = currentAthlete;
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"whosEval ==
%@", athleteSelected];
[request setPredicate:predicate];
NSEntityDescription *eval = [NSEntityDescription entityForName:@"Eval"
inManagedObjectContext:_managedObjectContext];
[request setEntity:eval];

No comments:

Post a Comment