Skip to content

Instantly share code, notes, and snippets.

@ninthspace
Created May 11, 2012 16:21
Show Gist options
  • Save ninthspace/2660742 to your computer and use it in GitHub Desktop.
Save ninthspace/2660742 to your computer and use it in GitHub Desktop.
Hooking up a NSFetchedResultsController
+ (NSFetchedResultsController *)fetchedResultsController:(id <NSFetchedResultsControllerDelegate>)delegate {
NSManagedObjectContext *context = [CACoreData sharedManagedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"MyModel" inManagedObjectContext:context]];
// must have a sort key
NSSortDescriptor *anySortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"someSortKey" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObjects:anySortDescriptor, nil]];
NSFetchedResultsController *newController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
newController.delegate = delegate;
return newController;
}
- (void)viewDidLoad
{
NSError *anyError = nil;
BOOL success = [self.fetchedResultsController performFetch:&anyError];
if( !success ) NSLog(@"Error = %@", anyError);
}
- (NSFetchedResultsController *)fetchedResultsController {
if (!fetchedResultsController ) {
// use this controller as the delegate for fetchedResultsController
fetchedResultsController = [MyStoreClass fetchedResultsController:self];
}
return fetchedResultsController;
}
// then add methods as required by the NSFetchedResultsControllerDelegate protocol
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment