pronebird
pronebird

Reputation: 12240

How to *keep track* of object count in CoreData

I'd like to keep track of the number of specific managed objects. The same way NSFetchedResultsController does except that I do not need any data back, I just need a number. What's the most efficient way to do this?

As a side note, apparently I don't want to use NSFetchedResultsController in the most straightforward way because it would create bunch of faults and clog memory for no reason.

I was trying to achieve this by marrying NSCountResultType and NSFetchedResultsController but I get some weird crash when merging contexts:

NSError *error;
auto defaultContext = [NSManagedObjectContext MR_defaultContext];
auto fetchRequest = [NotificationModel MR_requestAllWhere:NotificationModelAttributes.isRead isEqualTo:@NO];

fetchRequest.includesSubentities = NO;
fetchRequest.includesPropertyValues = NO;
fetchRequest.resultType = NSCountResultType;
fetchRequest.sortDescriptors = @[];
fetchRequest.propertiesToFetch = @[];

self.notificationCountFetchController = [NotificationModel MR_fetchController:fetchRequest delegate:self useFileCache:NO groupedBy:nil inContext:defaultContext];
[self.notificationCountFetchController performFetch:&error];
[MagicalRecord handleErrors:error];

Upvotes: 5

Views: 1243

Answers (3)

pronebird
pronebird

Reputation: 12240

All changes in MagicalRecord go through root context so I register for NSManagedObjectContextWillSaveNotification observation and fetch objects count on each save. Easy.

Upvotes: 2

Shahzaib Maqbool
Shahzaib Maqbool

Reputation: 1487

It’s really easy to get the number of results for a request with Core Data. When you only need the objects count it’s better to not fetch all the managed objects but just get the count. This is really easy with Core Data, instead of calling executeFetchRequest you have to call countForFetchRequest on your managedObjectContext.

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
NSError *error = nil;
return [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];

you can check also this answer at this link

Upvotes: 0

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

- countForFetchRequest:error: should suffice your needs

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
NSError *error = nil;
NSUInteger count = [managedObjectContext countForFetchRequest:fetchRequest error:&error];

Upvotes: 0

Related Questions