Created
August 15, 2012 20:39
-
-
Save happy-coding/3363416 to your computer and use it in GitHub Desktop.
Example fetchedResultsController in view controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma mark - Fetched results controller | |
- (NSFetchedResultsController *)fetchedResultsController | |
{ | |
if (fetchedResultsController != nil) { | |
return fetchedResultsController; | |
} | |
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; | |
// Edit the entity name as appropriate. | |
NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:self.managedObjectContext]; | |
[fetchRequest setEntity:entity]; | |
// Set the batch size to a suitable number. | |
[fetchRequest setFetchBatchSize:20]; | |
// Edit the sort key as appropriate. | |
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:NO]; | |
NSArray *sortDescriptors = @[sortDescriptor]; | |
[fetchRequest setSortDescriptors:sortDescriptors]; | |
// Edit the section name key path and cache name if appropriate. | |
// nil for section name key path means "no sections". | |
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"]; | |
aFetchedResultsController.delegate = self; | |
self.fetchedResultsController = aFetchedResultsController; | |
NSError *error = nil; | |
if (![self.fetchedResultsController performFetch:&error]) { | |
// Replace this implementation with code to handle the error appropriately. | |
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. | |
NSLog(@"Unresolved error %@, %@", error, [error userInfo]); | |
abort(); | |
} | |
return fetchedResultsController; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment