Cocoa Core Data efficient way to count entities

后端 未结 9 1747
滥情空心
滥情空心 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.

提交回复
热议问题