0

Is possible to observe the count of some Item, say Users, in Core Data?

I could do something like this.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDataModelChange:) name:NSManagedObjectContextObjectsDidChangeNotification object:myManagedObjectContext];

NSSet *insertedObjects = [[note userInfo] objectForKey:NSInsertedObjectsKey];
localCount += [insertedObjects count];

NSSet *deletedObjects = [[note userInfo] objectForKey:NSDeletedObjectsKey];
localCount -= [insertedObjects count];

But this seems error prone and their has to be a more direct solution.

4

1 回答 1

1

是的你可以。使用 NSFetchedResultsController 更容易。在正常情况下(我的意思是没有 NSFetchedResultsController)你会遵循

NSManagedObject *foo; //Some NSManagedObject
[foo addObserver: self forKeyPath:@"A" options: NSKeyValueObservingOptionOld |     NSKeyValueObservingOptionNew context:context];

将 NSFetchedResultsController 设置为委托,然后您将收到controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:呼叫。


编辑:在您的情况下,您的方法是正确的。错误必须来自其他地方

于 2012-08-16T14:20:43.090 回答