Database Reference
In-Depth Information
The
ZSContextWatcher
is publicly available under the BSD license, and the latest
version is always in my public GitHub repository at
http://github.com/ZarraStudios/
The goal of the
ZSContextWatcher
is to provide us with the ability to monitor a
subset of the data that is in Core Data and to be notified when it changes.
It's the same functionality that is in the
NSFetchedResultsController
but not as
tightly coupled with the
UITableView
.
@interface
ZSContextWatcher : NSObject
- (id)initWithManagedObjectContext:(NSManagedObjectContext*)context;
- (
void
)addEntityToWatch:(NSEntityDescription*)description
withPredicate:(NSPredicate*)predicate;
@end
The API to use this class is composed of two methods.
-initWithManagedObjectContext:
We initialize the
ZSContextWatcher
with an
NSManagedObjectContext
. This
NSManage-
dObjectContext
is used when it sets itself up as an observer on
NSNotificationCenter
.
This avoids notifications coming from other
NSManagedObjectContext
instances.
- (id)initWithManagedObjectContext:(NSManagedObjectContext*)context;
{
ZAssert(context, @
"Context is nil!"
);
if
(!(self = [super init]))
return
nil;
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:
@selector
(contextUpdated:)
name:NSManagedObjectContextDidSaveNotification
object:context];
return
self;
}
-addEntityToWatch: withPredicate:
The second method in the public API for the
ZSContextWatcher
allows us to define
what the watcher is listening for. This is moved away from the initialization
because I wanted the ability to watch more than one entity and/or more than
one predicate. With this method, I can add as many entities and/or predicates
as I need.