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];
All changes in MagicalRecord go through root context so I register for NSManagedObjectContextWillSaveNotification
observation and fetch objects count on each save. Easy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With