NSPredicate 和 NSInvalidArgumentException 中的 SUBQUERY [英] SUBQUERY in NSPredicate and NSInvalidArgumentException

查看:20
本文介绍了NSPredicate 和 NSInvalidArgumentException 中的 SUBQUERY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Core Data 中设置了以下模型.

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.

我设置了以下 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.

这是我收到的错误.

由于未捕获的异常而终止应用'NSInvalidArgumentException',原因:'无法解析格式字符串 "isSync == 0 AND SUBQUERY(toBookOrders, $x, $x.toBook == SELF)"

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.

推荐答案

问题的关键在于:

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

如果你把它分成两个子谓词,就像 Scott 建议的那样,你会得到:

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

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

问题是每个 SUBQUERY 都不会返回真或假,这是谓词必须的.它返回一个集合(一个数组),一个数组和真假不是一回事.因此,当您创建谓词时,您会收到一个错误,指出它是无效格式,因为 AND 之后的内容 不是谓词.这只是一个表达.

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.

可能想要:

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

这将为您提供一个谓词,以查找 isSync 为假的所有书籍,并且该书籍的 OrderBooks 中至少有一个是该书籍.

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.

这篇关于NSPredicate 和 NSInvalidArgumentException 中的 SUBQUERY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆