Database Reference
In-Depth Information
NSManagedObjectContext
associated with the
NSFetchedResultsController
changes, the
NSFetchedResultsController
checks to see whether any of the objects it is referencing
are impacted. Further, it also watches inserts to determine whether any
newly inserted objects should be included in what is being referenced. If any
changes occur, the
NSFetchedResultsController
notifies its delegate of the changes.
The delegate is normally its associated
UITableView
.
Standing Up an NSFetchedResultsController
The creation of a
NSFetchedResultsController
takes a number of steps and uses
several of the classes that we discussed in
Chapter 1,
Under the Hood of Core
Data
, on page 1
.
- (NSFetchedResultsController *)fetchedResultsController
{
if
(fetchedResultsController)
return
fetchedResultsController;
NSManagedObjectContext *moc = [self managedObjectContext];
NSFetchRequest *fetchRequest = nil;
fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@
"Recipe"
];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@
"name"
ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
NSFetchedResultsController *frc = nil;
frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:moc
sectionNameKeyPath:nil
cacheName:@
"Master"
];
[self setFetchedResultsController:frc];
[[self fetchedResultsController] setDelegate:self];
NSError *error = nil;
ZAssert([[self fetchedResultsController] performFetch:&error],
@
"Unresolved error %@\n%@"
, [error localizedDescription],
[error userInfo]);
return
fetchedResultsController;
}
The
NSFetchedResultsController
is effectively a wrapper around an
NSFetchRequest
.
Therefore, we first need to construct the
NSFetchRequest
that will be used. In
this example, we are building an
NSFetchRequest
that retrieves all of the available
recipes. Further, we are going to sort the
Recipe
entities based on their
name
attribute.