jdog
jdog

Reputation: 10779

Core Data KVO count

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.

Upvotes: 0

Views: 447

Answers (1)

wczekalski
wczekalski

Reputation: 745

Yes you can. It's even easier with NSFetchedResultsController. In normal case (I mean without NSFetchedResultsController) you do following

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

With NSFetchedResultsController set it's delegate, and then you will receive controller:didChangeObject:atIndexPath:forChangeType:newIndexPath: calls.


EDIT: in your case your approach is correct. The errors must come from somewhere else

Upvotes: 1

Related Questions