Database Reference
In-Depth Information
Figure 5—Stored fetch request
NSFetchRequest
, we can execute it in the same manner as we do with an
NSFetch
-
Request
that has been constructed in code.
NSManagedObjectContext *moc = [self managedObjectContext];
NSPersistentStoreCoordinator *psc = [moc persistentStoreCoordinator];
NSManagedObjectModel *model = [psc managedObjectModel];
NSFetchRequest *request = [model fetchRequestTemplateForName:@
"allIngredients"
];
NSMutableArray *sortArray = [NSMutableArray array];
[sortArray addObject:[[NSSortDescriptor alloc] initWithKey:@
"name"
ascending:YES]];
[request setSortDescriptors:sortArray];
As shown, we call the
-fetchRequestTemplateForName:
method on the
NSManagedOb-
jectModel
, which returns a fully formed
NSFetchRequest
to us. This
NSFetchRequest
will already have the
NSEntityDescription
and
NSPredicate
set, so we can execute
the
NSFetchRequest
immediately. We can also update this
NSFetchRequest
to include
sort descriptors if needed.
1.6
NSSortDescriptor
NSSortDescriptor
has been around longer than Core Data, and it is still quite
useful for ordering data. As mentioned previously, data that comes from a
to-many relationship is unordered by default, and it is up to us to order it.
For example, if we wanted to retrieve all the recipes and sort them by their
name property in alphabetical order, we would require an additional step as
part of the fetch.
NSFetchRequest *fetchRequest = nil;
fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@
"Recipe"
];