How to *keep track* of object count in CoreData

Ben*_*air 5 core-data objective-c ios magicalrecord

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];
Run Code Online (Sandbox Code Playgroud)

Ben*_*air 2

MagicalRecord 中的所有更改都会通过根上下文,因此我注册NSManagedObjectContextWillSaveNotification观察并在每次保存时获取对象计数。简单的。