Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8024237
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T22:48:29+00:00 2026-06-04T22:48:29+00:00

Currently using Core Data . I have one table in which I am trying

  • 0

Currently using Core Data. I have one table in which I am trying to retrieve information along these lines:

SELECT item, COUNT(*) FROM myTable GROUP BY item;

in order to produce this type of result:

+---------+------+-------+
| item        | COUNT(*) |
+---------+------+-------+
| group 1     |   2      |
| group 2     |   5      |
| group 3     |   8      |
+---------+------+-------+

I had the bright idea to use an NSExpression, with hopes of having Core Data do all the work for me. I am beginning to spin my wheels. The count: expression function is crashing on me. The exception is not very clear. The use of other expression functions, such as sum: doesn’t crash the app.

It would be nice to store the results in a NSFetchedResultsController. I’ve explored other options, none of which aren’t too appealing. Would it make more sense to write a SQL query and get it over with, rather than to use Core Data as a SQL wrapper in this case?

For your reference source code is below.

NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"item"];
NSExpression *totalExpression = [NSExpression expressionForFunction:@"count:" arguments:[NSArray arrayWithObject:keyPathExpression]];

NSExpressionDescription * totalExpressionDescription = [[NSExpressionDescription alloc] init];
[totalExpressionDescription setExpression:totalExpression];
[totalExpressionDescription setExpressionResultType:NSInteger64AttributeType];
[totalExpressionDescription setName:@"totalInstances"];

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"myEntity" inManagedObjectContext:self.managedObjectContext];
NSArray *propertiesToFetch = [[NSArray alloc] initWithObjects:strFieldName, totalExpressionDescription, nil];

[fetchRequest setEntity:entity];
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setPropertiesToFetch:propertiesToFetch];
[fetchRequest setFetchBatchSize:20];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:strFieldName ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

NSFetchedResultsController* aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[self managedObjectContext] sectionNameKeyPath:nil cacheName:nil];

...

NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error])
{
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T22:48:30+00:00Added an answer on June 4, 2026 at 10:48 pm

    This is possible with NSExpression as you originally proposed, in my contrived example I have an entity called “Person” with a property called “emailAddress” that I wish to get the count for.

    NSPropertyDescription *propDesc = [[[[model entitiesByName] objectForKey:@"Person"] propertiesByName] objectForKey:@"emailAddress"];
    NSExpression *emailExpr = [NSExpression expressionForKeyPath:@"emailAddress"];
    NSExpression *countExpr = [NSExpression expressionForFunction:@"count:" arguments:[NSArray arrayWithObject:emailExpr]];
    NSExpressionDescription *exprDesc = [[NSExpressionDescription alloc] init];
    [exprDesc setExpression:countExpr];
    [exprDesc setExpressionResultType:NSInteger64AttributeType];
    [exprDesc setName:@"count"];
    
    NSFetchRequest *fr = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    [fr setPropertiesToGroupBy:[NSArray arrayWithObject:propDesc]];
    [fr setPropertiesToFetch:[NSArray arrayWithObjects:propDesc, exprDesc, nil]];
    [fr setResultType:NSDictionaryResultType];
    NSArray *results = [moc executeFetchRequest:fr error:&error];
    

    I wrote a snippet of code to pre-populate the database with 1000 records:

    NSArray *emailAddresses = [NSArray arrayWithObjects:@"test@test.com", @"1@1.com", @"1@2.com", @"roam@test.com", @"foo@foo.com", nil];
        for (int i = 0; i < 1000; i++) {
            NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:moc];
            [person setValue:[NSNumber numberWithInt:i] forKey:@"aNumber"];
            [person setValue:[[NSUUID UUID] UUIDString] forKey:@"aUUID"];
            [person setValue:[emailAddresses objectAtIndex:(i % [emailAddresses count])] forKey:@"emailAddress"];
        }
    

    The above code will insert each email address 200 times, here are the results:

    2012-05-31 15:17:42.160 Scratch[16084:10d03] CoreData: sql: SELECT t0.ZEMAILADDRESS, COUNT( t0.ZEMAILADDRESS) FROM ZPERSON t0 GROUP BY  t0.ZEMAILADDRESS 
    2012-05-31 15:17:42.162 Scratch[16084:10d03] CoreData: annotation: sql connection fetch time: 0.0024s
    2012-05-31 15:17:42.163 Scratch[16084:10d03] CoreData: annotation: total fetch execution time: 0.0029s for 5 rows.
    (gdb) po results
    (NSArray *) $2 = 0x0f811280 <_PFArray 0xf811280>(
    {
        count = 200;
        emailAddress = "1@1.com";
    },
    {
        count = 200;
        emailAddress = "1@2.com";
    },
    {
        count = 200;
        emailAddress = "foo@foo.com";
    },
    {
        count = 200;
        emailAddress = "roam@test.com";
    },
    {
        count = 200;
        emailAddress = "test@test.com";
    }
    )
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application which is currently using and storing data in Core Data.
Hi I currently have a table view which is being filled via Core Data.
I'm currently facing in problem using Core Data. I have two entities A and
I'm currently developing an app that uses Core Data. I'm using two stores/configurations, one
I'm currently migrating my sqllite application to using core data. When I created the
Currently I have one managedContext, many NSArrayControllers of entities which are all pretty interrelated,
I'm trying to implement undo support using Core Data on the iPhone and I
I'm using core data on an iPhone application. I have multiple persisntent stores that
I have core data configuration in my iPhone app, and how I'm currently passing
I have a NSFetchedResultsController which displays data in a UITableView. I'm using the boiler

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.