开发者

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

开发者 https://www.devze.com 2023-01-06 08:44 出处:网络
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

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?

Than开发者_运维知识库ks,

-Aaron


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!


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

精彩评论

暂无评论...
验证码 换一张
取 消