Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ios - Core data subquery predicate

I'm trying to get a subquery predicate to work and I'm struggling.

I have two entities.

[League] <---->> [Game]

Game has a property kickOffDate.

I'd like to use a predicate to return all Leagues that have at least one Game with a kickOffDate today.

I am using this predicate...

// startOfDay and endOfDay are functions to return the given date with 00:00:00 and 23:59:59 respectively
NSPredicate *startOfDayPredicate = [NSPredicate predicateWithFormat:@"SUBQUERY(games, $g, $g.kickOffDate >= %@).@count > 0", [self startOfDay:[NSDate date]]];
NSPredicate *endOfDayPredicate = [NSPredicate predicateWithFormat:@"SUBQUERY(games, $g, $g.kickOffDate <= %@).@count > 0", [self endOfDay:[NSDate date]]];

NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[startOfDayPredicate, endOfDayPredicate]];

However, when I use this I don't seem to get any results.

Have I written the predicate correctly?

Is there a better way of doing this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Have you tried (untested):

[NSPredicate predicateWithFormat:@"SUBQUERY(games, $g, $g.kickOffDate >= %@ AND $g.kickOffDate <= %@).@count > 0", [self startOfDay:[NSDate date]],[self endOfDay:[NSDate date]]];

== League that have a game with a kick-off date in a given range

Your solution is equivalent to:

[NSPredicate predicateWithFormat:@"ANY games.kickOffDate >= %@ AND ANY games.kickOffDate <= %@",start,end];

== League that have a game that start after a given date and have a game that start before a given date (could be different games, or the same game)

Which should return more results than you like.

Edit:
As @Martin R suggested, you should verify that your data does indeed include a League answering the predicate to test it.
If you still get no results, check to see if there were errors during execution of the request and your data-stack is properly initialized.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...