Cocoa Core Data efficient way to count entities

后端 未结 9 1766
滥情空心
滥情空心 2020-11-30 16:45

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 s

9条回答
  •  醉酒成梦
    2020-11-30 17:45

    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;
    

提交回复
热议问题