Database Reference
In-Depth Information
In addition to the primary function of this class, we have a couple of conve-
nience methods that have proven useful. The first one,
-allParameters
, returns
an
NSDictionary
of all the parameters, including the defaults. In this method,
we create an
NSFetchRequest
for the
Parameter
entity without an
NSPredicate
. We
take the resulting
NSArray
from the fetch and loop over it. Within that loop, we
add each
NSManagedObject
to an
NSMutableDictionary
derived from the default
NSDictionary
. This ensures we have both the default values and the
Parameter
entries included in the final
NSDictionary
.
-allParameterNames
NSManagedObjectContext *moc;
NSError *error = nil;
moc = [[self associatedDocument] managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@
"Parameter"
inManagedObjectContext:moc]];
NSArray *params = [moc executeFetchRequest:request error:&error];
if
(error) {
DLog(@
"Error fetching parameter: %@\n%@"
, [error localizedDescription],
[error userInfo]);
return
nil;
}
NSMutableArray *keys = [[[self defaults] allKeys] mutableCopy];
for
(NSManagedObject *param in params) {
NSString *name = [param valueForKey:@
"name"
];
[keys addObject:name];
}
return
keys;
}
Like
-allParameters
,
-allParameterNames
is a convenience method that returns an
NSArray
of the keys currently set or defaulted. Just like the
-allParameters
method,
it retrieves all the parameter
NSManagedObject
objects and loops over them.
Within that loop, it adds the
name
property to an
NSMutableArray
derived from
the
defaults NSDictionary
.
10.3
Wrapping Up
With this design, we can access our parameters within each document without
having to worry about the underlying structure. We also don't need to stop
coding just to hop over and add a parameter to the object. We can work with
DocumentPreferences
in the same manner that we work with
NSUserDefaults
.