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
1.3k views
in Technique[技术] by (71.8m points)

ios - SUBQUERY in NSPredicate and NSInvalidArgumentException

I set up the following model in Core Data.

Book has a to-many relationship, called toBookOrders, with OrderBook entity. The inverse is called toBook.
Book has a BOOL value property called isSync.

I set up the following NSPredicate.

NSEntityDescription* entityDescription = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:moc];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"isSync == 0 AND SUBQUERY(toBookOrders, $x, $x.toBook == SELF)"];

Through this predicate I need to grab only books that haven't been synchronized and theirs relative orders.

This is the error I receive.

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "isSync == 0 AND SUBQUERY(toBookOrders, $x, $x.toBook == SELF)"

Any ideas? Thank you in advance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here's the crux of your problem:

@"isSync == 0 AND SUBQUERY(toBookOrders, $x, $x.toBook == SELF)"

If you split that up into the two subpredicates, as Scott suggests, you'll get:

  • isSync == 0
  • SUBQUERY(toBookOrders, $x, $x.toBook == SELF)

The problem is that every SUBQUERY does not return true or false, as a predicate must. It returns a collection (an array), and an array is not the same thing as true or false. Thus, when you create the predicate, you're getting an error that it's an invalid format, because the stuff after the AND isn't a predicate. It's simply an expression.

You're probably wanting:

@"isSync == 0 AND SUBQUERY(toBookOrders, $x, $x.toBook == SELF).@count > 0"

This would give you a predicate to find all the books where isSync is false and the at least one of the Book's OrderBooks is that Book.


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

...