1

I have an entity MyEntity that has a tags to-many relationship, so tags is an NSSet of MyEntity. It's optional, so some MyEntity's don't have tags. Here's what I'm trying to do:

 predicate= [NSPredicate predicateWithFormat:
 @"(rootId == parentId AND NONE tags.tagName == %@)", @"badTag"];

So I want to get all MyEntitys where rootId == parentId and don't give me any entities if its tags has a tag named "badTag". The problem with this is that if the entity does not have any tags at all, that entity is not returned. I've tried a variation of the above:

 @"(rootId == parentId AND ANY tags.tagName != %@)", @"badTag"];

But this gives the same result. How can I make this predicate work for the case where the entity does not have any tags at all?

Snowman
  • 31,411
  • 46
  • 180
  • 303
  • Do the entities that don't have tags, have a tags set that's nil, or no set at all. – rdelmar May 23 '12 at 00:53
  • They should just have the default value. They were never set, and I never tampered with them. – Snowman May 23 '12 at 01:16
  • I tested this code, but with custom objects rather than core data entities, and your first predicate worked under those conditions, with the tags set being nil (either set to nil explicitly or just not set). I don't know why it would be any different with entities. – rdelmar May 23 '12 at 03:22

2 Answers2

1

Perhaps adding an OR COUNT(tags) == 0 will get what you want?

If this is an SQL store, try turning on CoreData SQL debugging and see what is actually being run. XCode4 and Core Data: How to enable SQL Debugging

Community
  • 1
  • 1
Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102
1

You could solve this with a subquery predicate. Subqueries are extremely powerful once you master them. Sadly they're not well documented.

(rootId == parentId) AND (SUBQUERY(tag, $x, $x.tagName == %@).count() == 0)
Daniel Eggert
  • 6,665
  • 2
  • 25
  • 41