Graphics Programs Reference
In-Depth Information
In
BNRItemStore.m
, define
loadAllItems
to prepare and execute the fetch request
and save the results into the
allItems
array.
- (void)loadAllItems
{
if (!allItems) {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *e = [[model entitiesByName] objectForKey:@"BNRItem"];
[request setEntity:e];
NSSortDescriptor *sd = [NSSortDescriptor
sortDescriptorWithKey:@"orderingValue"
ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sd]];
NSError *error;
NSArray *result = [context executeFetchRequest:request error:&error];
if (!result) {
[NSException raise:@"Fetch failed"
format:@"Reason: %@", [error localizedDescription]];
}
allItems = [[NSMutableArray alloc] initWithArray:result];
}
}
In
BNRItemStore.m
, send this message to the
BNRItemStore
at the end of
init
.
[context setUndoManager:nil];
[self loadAllItems];
}
return self;
}
You can build to check for syntax errors. You will see a warning that
allAssetTypes
hasn't been implemented yet - that's okay for now.
In this application, you immediately fetched all the instances of the
BNRItem
entity. This
is a simple request. In an application with a much larger data set, you would carefully
fetch just the instances you needed. To selectively fetch instances, you add a
predicate
(an
NSPredicate
) to your fetch request, and only the objects that satisfy the predicate are
returned.
A predicate contains a condition that can be true or false. For example, if you only wanted
the items worth more than $50, you would create a predicate and add it to the fetch re-
quest like this:
NSPredicate *p = [NSPredicate predicateWithFormat:@"valueInDollars > 50"];
[request setPredicate:p];