Graphics Programs Reference
In-Depth Information
Adding BNRAssetTypes to Homepwner
In the model file, you described a new entity,
BNRAssetType
, that every item will have
a to-one relationship to. You need a way for the user to set the
BNRAssetType
of
BNRItem
s and create new
BNRAssetType
s. Also, the
BNRItemStore
will need a
way to fetch the
BNRAssetType
s. (Creating new
BNRAssetType
s is left as a chal-
lenge at the end of this chapter.)
In
BNRItemStore.h
, declare a new method.
- (NSArray *)allAssetTypes;
In
BNRItemStore.m
, define this method. If this is the first time the application is being
run - and therefore there are no
BNRAssetType
s in the store - create three default
types.
- (NSArray *)allAssetTypes
{
if (!allAssetTypes) {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *e = [[model entitiesByName]
objectForKey:@"BNRAssetType"];
[request setEntity:e];
NSError *error;
NSArray *result = [context executeFetchRequest:request error:&error];
if (!result) {
[NSException raise:@"Fetch failed"
format:@"Reason: %@", [error localizedDescription]];
}
allAssetTypes = [result mutableCopy];
}
// Is this the first time the program is being run?
if ([allAssetTypes count] == 0) {
NSManagedObject *type;
type = [NSEntityDescription insertNewObjectForEntityForName:@"BNRAssetType"
inManagedObjectContext:context];
[type setValue:@"Furniture" forKey:@"label"];
[allAssetTypes addObject:type];
type = [NSEntityDescription insertNewObjectForEntityForName:@"BNRAssetType"
inManagedObjectContext:context];
[type setValue:@"Jewelry" forKey:@"label"];
[allAssetTypes addObject:type];
type = [NSEntityDescription insertNewObjectForEntityForName:@"BNRAssetType"
inManagedObjectContext:context];
[type setValue:@"Electronics" forKey:@"label"];