views:

44

answers:

2

So, I've got a one-to-many relationship of Companies to Employees in CoreData (using a SQLite backend on iOS, if that's relevant). I want to create a predicate that only returns Companies that have 0 Employees associated with them. I could do it by getting all the Companies and iterating over them, but that would be (I assume) much slower.

Any ideas?

Thanks,
-Aaron

+1  A: 

Assuming your Company -> Employee relationship is named "employees"

NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Company" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];

// the following doesn't work
// NSPredicate *noEmployeesPredicate = [NSPredicate predicateWithFormat:@"employees = nil OR employees[SIZE] = 0"];

// use @count instead
NSPredicate *noEmployeesPredicate = [NSPredicate predicateWithFormat:@"employees = nil OR employees.@count == 0"];
[request setPredicate:predicate];

NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (error)
{
    // Deal with error...
}
falconcreek
Thanks for the suggestion. Unfortunately, when I ran it, I got `'NSInvalidArgumentException', reason: 'to-many key not allowed here'`This led to some googling, which turned up the result that I posted as the answer. I think the problem is that I'm using a one-to-many relationship.Anyways, much thanks!
Aaron Lynch
+1  A: 

After trying @falconcreek's answer and getting an error (described in my comment on his answer), I did some googling and determined that the answer was

NSPredicate *noEmployeesPredicate = [NSPredicate predicateWithFormat:@"employees.@count == 0"];

Now everything works über efficiently. Thanks!

Aaron Lynch
excellent. I was looking for the @count function in the docs. it is still worthwhile to check for nil relationships as well.
falconcreek