views:

16

answers:

1

Lets say I have an employees relationship in an Company entity, and it's to-many. And they're really many. Apple in 100 years, with 1.258.500.073 employees.

Could I simply do something like

NSInteger numEmployees = [apple.employees count];

without firing 1.258.500.073 faults? (Well, in 100 years, the iPhone will easily handle so many objects, for sure...but anyways)

+1  A: 

-count will not fire a fault. If you already have the parent object in memory then yes this is the best way to get that count.

If you do not have the objects in memory then the more performant way would be:

NSManagedObjectContext *moc = ...;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"child" inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:@"parent == %@", parent]];
NSError *error = nil;
NSInteger count = [moc countForFetchRequest:request error:&error];
NSAssert2(error == nil, @"Error fetching request: %@\n%@", [error localizedDescription], [error userInfo]);
[request release], request = nil;

Which performs a count at the database level.

Marcus S. Zarra