我想跟踪特定托管对象的数量。与 NSFetchedResultsController
的方式相同,只是我不需要返回任何数据,我只需要一个数字。最有效的方法是什么?
作为旁注,显然我不想以最直接的方式使用 NSFetchedResultsController
,因为它会无缘无故地产生一堆错误和阻塞内存。
我试图通过结合 NSCountResultType
和 NSFetchedResultsController
来实现这一点,但是在合并上下文时我遇到了一些奇怪的崩溃:
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];
最佳答案
MagicalRecord 中的所有更改都通过根上下文进行,因此我注册了 NSManagedObjectContextWillSaveNotification
观察并在每次保存时获取对象计数。很简单。
关于ios - 如何*跟踪* CoreData 中的对象计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32606041/