views:

2840

answers:

2

Hello, i read much about Core Data.. but what is an efficient way to make a count over an Entity-Type (like SQL can do with SELECT count(1) ...). Now i just solved this task with selecting all with NSFetchedResultsController and getting the count of the NSArray! I am sure this is not the best way...

thank you

+17  A: 

I don't know whether using NSFetchedResultsController is the most efficient way to accomplish your goal (but it may be). The explicit code to get the count of entity instances is below:

// assuming NSManagedObjectContext *moc

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:moc]];

[request setIncludesSubEntities:NO]; //Omit subentities. Default is YES (i.e. include subentities)

NSError *err;
NSUInteger count = [moc countForFetchRequest:request error:&err];
if(count == NSNotFound) {
  //Handle error
}

[request release];
Barry Wark
On Leopard you want to use countForFetchRequest: and not executeFetchRequest:
IlDan
Yes! Thank you. I'll update the code.
Barry Wark
And skip to set the predicate. No predicate: get all the objects that match the entity description
IlDan
Just FYI, count == 0 if there are no results for the specific request, NSNotFound = NSIntegerMax, so '//Handel error' will not be executed if there are no results.
Ben
+9  A: 

To be clear, you aren't counting entities, but instances of a particular entity. (To literally count the entities, ask the managed object model for the count of its entities.)

To count all the instances of a given entity without fetching all the data, the use -countForFetchRequest:.

For example:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity: [NSEntityDescription entityForName: entityName inManagedObjectContext: context]];

NSError *error = nil;
NSUInteger count = [context countForFetchRequest: request error: &error];

[request release];

return count;
Jim Correia