Core Data, check for existing Many-To-Many relationship
Having trouble with my first Core Data project...
I have two entities in a many to many relationship: Quotes <<--->> Boilers.
When a user selects a Boiler in a UITableView row I want to know if that Boiler already has a relationship with the Quote that the page is managing, and toggle that relationship.
I think the code below fails because the Predicate doesn't know which Boiler has been selected, but I can't quite get this right...
- (void)managedObjectSelected:(NSManagedObject *)managedObject
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Boiler" inManagedObjectContext:managedObject.managedObjectContext]];
request.predicate = [NSPredicate predicateWithFormat:@"ANY myQuote =开发者_StackOverflow %@", quote];
NSError *error;
NSUInteger count = [managedObject.managedObjectContext countForFetchRequest:request error:&error];
if(count==0){
[quote addMyBoilersObject:(Boiler*) managedObject];
}
else {
[quote removeMyBoilersObject:(Boiler*) managedObject];
}
[managedObject.managedObjectContext save:&error];
}
Any help or pointers would be greatly appreciated...
One way to approach this is to use an NSFetchedResultsController to populate your UITableView. If you do this, then you should be able to toggle selection in
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Get the Boiler that was selected.
Boiler *boiler = (Experiment *) [fetchedResultsController objectAtIndexPath:indexPath];
if (boiler)
{
if ([[self quote] boilers] containsObject:boiler])
{
// connected, so disconnect
}
else
{
// disconnected, so connect
}
}
}
Anyway, have you tried something like this?
精彩评论