否定 Core Data NSPredicate 关系时出现问题
我对此感到摸不着头脑。我有一个解决办法,但我不明白,所以这不算数。我想要做的是对于实体(在本例中是“照片”),我想找到除指定用户之外的任何人评论的所有照片。这里的关系是照片->评论->用户,一张照片可以有多个评论,每个评论都属于一个用户。前两个例子是我合乎逻辑的第一次尝试,但不起作用。我发现一些类似的代码显示了子查询的工作原理,但是任何人都可以解释为什么前两个示例不起作用?
// this does not work
[NSPredicate predicateWithFormat:@"NOT (ANY reviews.user = %@)", self.user]
// this does not work
[NSPredicate predicateWithFormat:@"NONE reviews.user = %@", self.user]
// this works
[NSPredicate predicateWithFormat:@"SUBQUERY(reviews, $x, $x.user == %@).@count == 0", self.user];
I'm scratching my head on this one. I have a work around, but I don't understand it so that doesn't count. What I want to do is for the entity (in this case a "Photo" lets say), I want to find all the Photos reviewed by anyone OTHER than the specified user. The relationship here is Photo->Review->User, where a photo can have multiple reviews, and each review is owned by exactly one user. The first two examples were my logical first attempts, but does not work. I found some similar code that shows the subquery which works, but can anyone explain why the first two examples don't work?
// this does not work
[NSPredicate predicateWithFormat:@"NOT (ANY reviews.user = %@)", self.user]
// this does not work
[NSPredicate predicateWithFormat:@"NONE reviews.user = %@", self.user]
// this works
[NSPredicate predicateWithFormat:@"SUBQUERY(reviews, $x, $x.user == %@).@count == 0", self.user];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个
try this
问题是您想要比较谓词中的关系而不是属性。您的
用户
应该有一个唯一的属性,例如name
。我建议您按以下方式在谓词中使用它:The problem is that you want to compare relationships in your predicate rather than attributes. Your
User
should have a unique attribute, such asname
. I suggest that you use it in your predicate in the following way:我发现通过比较相关实体的唯一标识符而不是实体本身来执行核心数据关系比较更好。例如,在我的应用程序中,我有一个名为
User
的实体,它具有属性objectId
。 (注意:不要将其与 Core Data 对象的内部objectID
混淆。objectId
只是我的外部数据库中的唯一主键。然后,您的谓词看起来像这样:I find it is better to perform Core Data relationship comparisons by comparing unique identifiers of the entity in question rather than the entity itself. For example, in my app I have an entity called
User
, which has an attributeobjectId
. (Note: this is not to be confused with the internalobjectID
of the Core Data object. TheobjectId
is simply a unique primary key from my external DB. Then, your predicate would look like this: