开发者

Difference between getting an Object using FetchResultController and ManagedObjectContext

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜