Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 456
Rob Zombie Avatar asked Oct 30 '22 19:10

Rob Zombie


1 Answers

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

like image 108
Rob Zombie Avatar answered Nov 14 '22 10:11

Rob Zombie