Cocoa Core Data efficient way to count entities

后端 未结 9 1719
滥情空心
滥情空心 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:42

    I'll just add that to make it even more efficient... and because its just a count, you don't really need any property value and certainly like one of the code examples above you don't need sub-entities either.

    So, the code should be like this:

    int entityCount = 0;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"YourEntity" inManagedObjectContext:_managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entity];
    [fetchRequest setIncludesPropertyValues:NO];
    [fetchRequest setIncludesSubentities:NO];
    NSError *error = nil;
    NSUInteger count = [_managedObjectContext countForFetchRequest: fetchRequest error: &error];
    if(error == nil){
        entityCount = count;
    }
    

    Hope it helps.

    0 讨论(0)
  • 2020-11-30 17:43

    If you want to find count for specific predicated fetch, i believe this is the best way:

    NSError *err;
    NSUInteger count = [context countForFetchRequest:fetch error:&err];
    
    if(count > 0) {
    NSLog(@"EXIST"); 
    } else {
    NSLog(@"NOT exist");
    }
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题