I noticed there are two different fetch requests in one complete Core Data process.
Fetch request A:
a Context (MOC) instance fetches data from disk to memory by creating a fetch request and executing it (executeFetchRequest).
Fetch request B:
a FRC instance is init with another fetch request, fetching data from memory ( specify a context) to memory, which happens automatically so no need to “execute” this fetch.
Connection between Fetch request A and Fetch request B
1.A and B’s contexts must be the same one
2.The result of fetch B is a subset of result of fetch A
Question
I want to know if my understanding is absolutely correct. Please point out any inaccurate statement and misconception. Thanks.
Sample code
Fetch A (executed explicitly): from disk to memory
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
request.predicate = [NSPredicate predicateWithFormat:@"unique = %@", [flickrInfo
objectForKey:FLICKR_PHOTO_ID]];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
// execute the fetch
NSArray *matches = [context executeFetchRequest:request error:&error];
Fetch B (automatcally): from memory to memory
- (void)setupFetchedResultsController
{
NSFetchRequest *request =
[NSFetchRequest fetchRequestWithEntityName:@"Photo"];
request.sortDescriptors =
[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"title"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)]];
request.predicate = [NSPredicate predicateWithFormat:@"whoTook.name = %@", self.photographer.name];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.photographer.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
}
Fetch Request A. Correct.
Fetch Request B. Almost correct. You don’t know where FRC is getting the data, if it is in memory or has to be retrieved from the store. You don’t have to care, that’s the beauty of FRC.
Relationship 1. Same Context. Wrong. The context has nothing to do with the relationship. The two entities A and B have to be in the same data model, not context. The context is primarily for fetching and saving.
Relationship 2. Subset. Wrong. If you fetch entity A, you have access to its relationships, but you do not know how much data is actually being retrieved at which time (this is called faulting). Core data is going to take care of that for you. Because relationships could be set up any way (one-to-many, many-to-many, one-to-one) and could be empty, your statement about subsets is not correct. For example:
In this case the set contains indeed a subset of all B entities (if there are other ones), but you see that this is just a special case. In the above code you can also see how conveniently you can access the relationship entities via dot-notation.