Database Reference
In-Depth Information
- (
void
)addEntityToWatch:(NSEntityDescription*)description
withPredicate:(NSPredicate*)predicate;
{
NSPredicate *entityPredicate = nil;
NSPredicate *final = nil;
NSArray *array = nil;
entityPredicate = [NSPredicate predicateWithFormat:@
"entity.name == %@"
,
[description name]];
array = [NSArray arrayWithObjects:entityPredicate, predicate, nil];
final = [NSCompoundPredicate andPredicateWithSubpredicates:array];
if
(![self masterPredicate]) {
[self setMasterPredicate:finalPredicate];
return
;
}
array = [NSArray arrayWithObjects:[self masterPredicate], final, nil];
finalPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:array];
[self setMasterPredicate:finalPredicate];
}
We do a bit of
NSPredicate
construction in the implementation. First, we take
the passed-in
NSEntityDescription
and use that inside a new predicate that com-
pares the entity name. Next, we create a compound predicate that combines
the passed-in predicate with the newly created entity predicate with an AND
join. Now we have a new predicate that checks to make sure the compared
object is the same entity before we use the second part of the predicate against
the object.
Why do we do this? If we just run the passed-in predicate against every object,
we would get an error when it hits an object that doesn't have one of the
properties in the predicate. By adding a prefix predicate that checks the name
of the entity, we are ensuring it will run only against the correct entity.
If there is no existing predicate in our
ZSContextWatcher
, we set our new com-
pound predicate as the
masterPredicate
and return. However, if there is already
a
masterPredicate
set, we need to compound the existing predicate with our new
one. Again, we use an
NSCompoundPredicate
to combine the existing
masterPredicate
and our new predicate. However, this time we use an OR instead of an AND
in the compound predicate. Finally, we take the newly created compound
predicate and set that as the
masterPredicate
.
-contextUpdated:
We have constructed a predicate that we can run against a collection of
NSManagedObject
instances, and it will filter out any objects that we do not care