How to count in coredata (aggregation)?

后端 未结 2 1194
执念已碎
执念已碎 2021-02-06 11:01

I am learning core data and particularly working on aggregation.

Current what I want to do : count the number of records from the table which is in to-many relations

2条回答
  •  滥情空心
    2021-02-06 11:38

    I had to count about 10 000 entities and it slowed down my interface responsiveness a lot while doing it with countForFetchRequest..

    Here is a way of doing it wth NSExpression:

    - (NSUInteger) unfilteredFCsCount {
    
    // Just the fetchRequest
        NSFetchRequest *fetchRequest = [self unfilteredFCsFetchRequest];
    
        [fetchRequest setResultType: NSDictionaryResultType];
    
    // You can use any attribute of the entity. its important, because you are not counting 
    // the properties, but actually the entities
        NSExpression *keyPathExpression = [NSExpression expressionForKeyPath: @"sortIndex_"]; // Does not really matter
        NSExpression *maxExpression = [NSExpression expressionForFunction: @"count:" 
                                                                arguments: [NSArray arrayWithObject:keyPathExpression]];
        NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
        [expressionDescription setName: @"fcCount"];
        [expressionDescription setExpression: maxExpression];
        [expressionDescription setExpressionResultType: NSInteger32AttributeType];
    
        [fetchRequest setPropertiesToFetch: [NSArray arrayWithObject:expressionDescription]];
    
        NSUInteger fcCount = 0;
        NSError *error = nil;
        NSArray *results = nil;
        results = [self.managedObjectContext executeFetchRequest: fetchRequest error: &error];
        KSLog(KSLogLevelDebug, @"unfilteredFCsCount results: %@", results);
    
        if([results count] > 0) {
            NSNumber *count = [[results objectAtIndex: 0] objectForKey: @"fcCount"];
            fcCount = [count intValue];
        }
    
        return fcCount;
    }
    

提交回复
热议问题