views:

150

answers:

2

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]; 
A: 

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.

FenchKiss Dev
Thanks. But the Array returned by this two methods are the same, aren't they?? The questions is about it: the difference about the return. I tested after asking and I think it is.
wal
A: 

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.

Marcus S. Zarra
Thanks man!....
wal