Question

What's the difference between get elements from Core Data with FetchResultController or ManagedObjectContext??

1) FetchResultController

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Item" inManagedObjectContext: managedObjectContext]]; 

NSSortDescriptor *sortDescriptorNameAscending = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptorNameAscending,nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptorNameAscending release];

NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Lists"]; 

2) ManagedObjectContext

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
[request setEntity:[NSEntityDescription entityForName:@"Item"  inManagedObjectContext:managedObjectContext]]; 
NSError *error = nil; 
NSArray *items = [ managedObjectContext executeFetchRequest:request error:&error]; 
Was it helpful?

Solution

The point behind using an NSFetchedResultsController as opposed to just a NSFetchRequest is the monitoring of your data and the convenience methods when working with sections.

When dealing with just a NSFetchRequest you have to determine the sections yourself and you need to refetch your data when something changes.

When dealing with the NSFetchedResultsController, it will determine your sections, cache the results (making a second request for that data near instantaneous), and provide convenience methods for your NSTableView. Finally, when your data changes, the NSFetchedResultsController will notify you through its delegates.

The data internal to both of these is going to be the same. It is managing the state of that data that is the difference.

OTHER TIPS

The NSFetchedResultsController object will tell you when the objects of your query change. Just provide a delegate object to receive the calls (see the doc for NSFetchedResultsControllerDelegate protocol). It also provide you with section management which is useful if you want to display the data in a table view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top