我是NSPredicate的新手,所以如果有人会告诉我我是否正确的方式,我将不胜感激。
问题:(类是NSManagedObject的子类)
我有一个玩家类这个字段:
@property (nonatomic, retain) NSSet *hisNumbers; //it's a set of Numbers
数字类是这样的:
@property (nonatomic, retain) NSNumber * first;
@property (nonatomic, retain) NSNumber * second;
@property (nonatomic, retain) Season *forSeason; //it's one-to-one relationship with a Season Object
@property (nonatomic, retain) Player *owner; //one-to-one with Player
@property (nonatomic, retain) NSNumber * isPresent;
季节类有以下参数:
@property (nonatomic, retain) NSSet *seasonGames; //set of Game
@property (nonatomic, retain) NSSet *numbers; //set of Numbers (inverse of forSeason)
我正在尝试做的是一种采用赛季对象并让我回到那个赛季所有球员的方法...... 这是我的尝试:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Player" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"nameLast" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ANY SELF.hisNumbers.isPresent == %@) AND (ANY SELF.hisNumbers IN %@)",[NSNumber numberWithBool:YES],season.numbers];
但它不起作用..查询的两个部分似乎分开工作,但也许这只是一个巧合...
现在它返回每个拥有标记'isPresent == YES'的数字的玩家和另一个具有'season.numbers'成员的数字。相反,我需要的是能够同时匹配两个标准的单个“数字”的球员......
如果您需要更多详情,请与我们联系。谢谢大家
答案 0 :(得分:6)
对于数量为isPresent == YES
且可能不同的号码属于season.numbers
的玩家,您的谓词属实。
要查找具有(至少一个)符合两个条件的号码的玩家,您可能必须使用SUBQUERY(至少我不知道更简单的解决方案)。
您也可以简化
"hisNumbers IN %@", season.numbers
到
"hisNumbers.forSeason == %@", season
这给出了以下谓词,希望对你有用:
[NSPredicate predicateWithFormat:@"SUBQUERY(hisNumbers, $x, $x.isPresent == %@ AND $x.forSeason == %@).@count > 0",
[NSNumber numberWithBool:YES], season]
(参见“NSExpression类参考”中的expressionForSubquery:usingIteratorVariable:predicate:,其中记录了类似的问题和SUBQUERY解决方案。)