views:

20

answers:

2

Hello,
I'm using NSFetchedResultsController and I have a problem to query count in parent attribute.

Assuming that following data model, 'Group', 'Category', 'Item'.
- Item : All items belong to ‘Category’
- Category : ‘Category’ may belong to a certain ‘Group’
- Group : 'Group' has zero to N 'Category'

And I want to search all items which does not have any groups in category.
My codes are following :

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
...
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"((category.groups.@count == 0) || category.categoryId == %@)", categoryId];
...

But, "category.groups.@count" does not work in here. (It works well out of NSFetchedRequest)
How can I solve this problem. Please help me;;

Thanks.

A: 

You open 2 brackets, and close only one:

...@"((category.groups.@count == 0) || category.categoryId == %@"...
jamapag
Oops ! It's just my typing mistake. However this problem does not solved. Anyway thanks for your reply.
likejy
A: 

A relationship can also be nil.

(((category.groups.@count == 0) || category.groups == nil) || category.categoryId == %@)

The resolution of the code inside of the predicate when you are running against a SQLite backend can be different than what you expect inside of Objective-C directly. When you run into odd things like this it can be helpful to turn on sql debugging to see what the underlying sql is and adjust your predicates accordingly.

Marcus S. Zarra
Thanks for your reply. but the codes are crashed... "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'". By the way, how to turn on sql debugging ?
likejy
Does Item have to-one relationship with Category? You can turn on debug via reading the Apple docs and [my post over on PragProg](http://forums.pragprog.com/forums/90/topics/4649).
Marcus S. Zarra