Database Reference
In-Depth Information
In this method, we receive the name of the value that the caller is attempting
to retrieve. We use this name to retrieve the
NSManagedObject
via the
-findParameter:
method and return the
NSManagedObject
object's
value
property. If there is no
parameter with the passed-in name, we check the
defaults NSDictionary
to see
whether there is a default for it. If there is no default set, we let the
-valueForKey:
method return
nil
to the caller.
-findParameter:
- (NSManagedObject*)findParameter:(NSString*)name;
{
NSManagedObjectContext *moc;
NSManagedObject *param;
NSError *error = nil;
moc = [[self associatedDocument] managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@
"Parameter"
inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:@
"name == %@"
, name]];
param = [[moc executeFetchRequest:request error:&error] lastObject];
if
(error) {
DLog(@
"Error fetching parameter: %@\n%@"
, [error localizedDescription],
[error userInfo]);
return
nil;
}
[request release], request = nil;
return
param;
}
In the
-findParameter:
method, we construct an
NSFetchRequest
against the
parameters table using a compare on the
name
property to filter it down to a
single result. Assuming there is no error on the fetch, we return the
NSManage-
dObject
. In this method, we are using the
-lastObject
method on the resulting
array as a convenience.
-lastObject
automatically checks for an empty array
and returns
nil
if the array is empty. This reduces the code complexity and
gives us the result we want in a single call. If there is an error accessing the
Core Data stack, we report the error and return
nil
. Note that we do not create
a parameter if there is not one in this method. We intentionally separate this
out so that we are not creating potentially empty parameters. This allows us
to request a parameter and check whether it is
nil
without the concern of
parameters being generated unnecessarily.