JSA986
JSA986

Reputation: 5936

Core Data, Get Sum Of Certain Boolean Value Attribute

I'm logging a Core Data attribute "passed" (Boolean value)

for (Circuit *object in self.distributionBoard.circuits) {
        NSLog(@"Core Data Value =  %d", object.passed);


    }

This logs fine. What's the most efficient way to count the number of times the saved boolean value == 1?

Using NSFetchReques or NSExpression did not yield the desired result so far. Looked here: Core Data sum of all instances attribute and similar, with the usual searches

Upvotes: 1

Views: 63

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70946

Since your property is a boolean, you can make it a lot simpler than the methods described in that answer. Use a predicate to match the value of passed and then get the count of the result instead of the fetched objects. Something like:

NSFetchRequest<Event *> *fetchRequest = MyEntity.fetchRequest;
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"passed = true"];
NSError *error = nil;
NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];

Then count has the number of instances where passed is true.

Upvotes: 2

Related Questions