5

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.

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190

2 Answers2

25

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.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
-2

Separate the isSync == 0 and SUBQUERY into separate NSPredicates, add them to an NSArray then use [NSCompoundPredicate andPredicateWithSubpredicates:array] to get them joined into a single one to pass to your NSFetchSpecification.

Scott Corscadden
  • 2,831
  • 1
  • 25
  • 43
  • Thank you. The problem is still there. Maybe it's not possible to use *SELF* in subqueries. Thank you. – Lorenzo B Mar 21 '12 at 15:09
  • Here's how I've used it: `[NSPredicate predicateWithFormat:@"SUBQUERY(childItems, $child, $child.columnName IN %@).@count != 0", arrayOfThingsToMatchOn]`. Self should be implicit, I think. – Scott Corscadden Mar 21 '12 at 18:38
  • -1 This is no different than using `AND` in the predicate format. – Dave DeLong Mar 21 '12 at 22:09