Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

ios - Core Data: NSPredicate for many-to-many relationship. ("to-many key not allowed here")

I have two entities named "Category" and "Article" which have a many to many relationship. I want to form a predicate which searches for all articles where category.name is equal to some value. I have the following:

 NSEntityDescription  *entityArticle   = [NSEntityDescription entityForName:@"Article" inManagedObjectContext:managedObjectContext]; 
 NSSortDescriptor  *sortDescriptor   = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
 NSArray     *sortDescriptors  = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
 NSPredicate    *predicate    = [NSPredicate predicateWithFormat:@"categories.name == [cd] %@", category.name]; 

 [request setSortDescriptors:sortDescriptors];
 [request setEntity:entityArticle];
 [request setPredicate:predicate];

 NSMutableArray *results = [[managedObjectContext executeFetchRequest:request error:nil] mutableCopy];

 if ([results count] > 0)
  NSLog(@"Results found."); 
 else 
  NSLog(@"NO results found."); 

 [request release];
 [sortDescriptor release];
 [sortDescriptors release];

The error I receive is *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'

Are there any options to retrieve the desired data?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're trying to compare a collection (categories.name) to a scalar value (category.name). You need to either use a collection comparator (CONTAINS), or use a predicate modifier (ANY/ALL/SOME, etc).

Try using:

[NSPredicate predicateWithFormat:@"ANY categories.name =[cd] %@", category.name];

Or:

[NSPredicate predicateWithFormat:@"categories.name CONTAINS[cd] %@", category.name];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...