1. Build your own
Core Data Observer
Zach McArtor, @zmcartor, http://hackazach.net
2. Wat?
• Small component that notifies us of
NSManagedObject changes/saves
• React to those changes via method invocation
3. Why?
• Sometimes, an NSFetchedResultsController
won’t cut it
• Want to update a tiny piece of UI or run a
background action
• Be reactive!
4. Relevant Notifications
Fired by NSManagedObjectContext
• NSManagedObjectContextObjectsDidChangeNotification
• NSManagedObjectContextDidSaveNotification
5. Subscribe, and ye shall receive
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(contextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:SomeManagedObjectContext];
6. An NSDict of Changes!
• NSDict keyed by these constants:
• { NSInsertedObjectsKey,
• NSUpdatedObjectsKey
• NSDeletedObjectsKey. }
7. Last step, add a predicate
• Subscribing to didChange/DidSave triggers a
callback for every model save/change. We only
care about a subset of models.
• Abstract notification subscription into Class
• Predicate filter models returned in NSDict. (Protip!)
8. Dealing Concurrency With
• There are different ways to set up a concurrent
Core Data stack :(
!
!
!
http://floriankugler.com/blog/2013/4/2/theconcurrentcoredatastack
https://www.cocoanetics.com/2012/07/multi-context-coredata/
9. Which context to subscribe?
• ‘didSave’ notifications fired during context save
(duh.) Going up chain child->parent
• ’didChange’ notifications fired when context
merges changes (MagicalRecord merges down into default context)
10. Watch out!
• The managedObjects received via notification
may not be in the correct context for use on
main thread.
• Use existingObjectWithId:error: to pull into
correct context
• Subscribe to a single context, don’t listen for
every event within a nested system