Aaron Rennow
Aaron Rennow

Reputation: 95

How to determine number of objects in one-to-many relationship in CoreData

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

Upvotes: 0

Views: 266

Answers (2)

falconcreek
falconcreek

Reputation: 4170

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...
}

Upvotes: 0

Aaron Rennow
Aaron Rennow

Reputation: 95

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!

Upvotes: 2

Related Questions