核心数据:NSPredicate用于多对多关系。 (“在这里不允许多个密钥”) [英] Core Data: NSPredicate for many-to-many relationship. ("to-many key not allowed here")
问题描述
我有两个名为类别和文章的实体,它们具有多对多的关系。我想形成一个谓词,搜索其中category.name等于某个值的所有文章。我有以下:
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];
我收到的错误是 ***由于未捕获异常终止应用程序' NSInvalidArgumentException',原因:'to-many key not allowed here'
有没有任何选项来检索所需的数据?
Are there any options to retrieve the desired data?
推荐答案
您尝试将一个集合( categories.name
)与标量值( category.name
)。您需要使用集合比较器( CONTAINS
),或使用谓词修饰符( ANY
/ ALL
/ SOME
等)。
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).
尝试使用:
[NSPredicate predicateWithFormat:@"ANY categories.name =[cd] %@", category.name];
或:
[NSPredicate predicateWithFormat:@"categories.name CONTAINS[cd] %@", category.name];
这篇关于核心数据:NSPredicate用于多对多关系。 (“在这里不允许多个密钥”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!