iOS: Two Entities - Fetch, Merge, and Sort - sorting

I need to perform a fetch from two different entities, merge them, and then sort them based on a field that both entities have: 'lastModifiedDate'. lastModifiedDate is NSDate
NSFetchRequest *fetchRequest1 = [[NSFetchRequest alloc] init];
NSFetchRequest *fetchRequest2 = [[NSFetchRequest alloc] init];
NSEntityDescription *entity1 = [NSEntityDescription entityForName:#"Entity1" inManagedObjectContext:self.managedObjectContext];
[fetchRequest1 setEntity:entity1];
NSEntityDescription *entity2 = [NSEntityDescription entityForName:#"Entity2" inManagedObjectContext:self.managedObjectContext];
[fetchRequest2 setEntity:entity2];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"lastModeifiedDate" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[fetchRequest1 setSortDescriptors:sortDescriptors];
[fetchRequest2 setSortDescriptors:sortDescriptors];
[self.managedObjectContext executeFetchRequest:fetchRequest onSuccess:^(NSArray *results) {
[self.refreshControl endRefreshing];
self.objects = results; //objects is an array #property
[self.tableView reloadData];
} onFailure:^(NSError *error) {
[self.refreshControl endRefreshing];
NSLog(#"An error %#, %#", error, [error userInfo]);
}
I'm stuck here. I need to merge fetchRequest1 and fetchRequest2, and have the objects display in a tableViewController in descending order. Thanks.

You can not merge two fetch requests, but you could merge and sort the fetched arrays:
NSArray *results1 = ...; // from first fetch request;
NSArray *results2 = ...; // from second fetch request;
NSMutableArray *merged = [[NSMutableArray alloc] init];
[merged addObjectsFromArray:results1];
[merged addObjectsFromArray:results2];
[merged sortUsingDescriptors:#[sortDescriptor]];
Alternatively, you could define an entity "Entity", make that the parent entity
for "Entity1" and "Entity2", and define all common properties (such as
"lastModifiedDate") in the parent entity. Then you can fetch and sort "Entity" objects.
(A possible disadvantage of entity inheritance is that Core Data uses a single table for all
"Entity", "Entity1" and "Entity2" objects. This is not optimal if there are many
properties that are not common to both.)

Related

Having Trouble Sorting CoreData backed NSArrayController

Im trying to retrieve an array of sorted objects from my Core Data backed NSArrayController. Once the ManagedObjectContext is ready I fire a Notification which the object owning the NSArrayController listens for and then sets up the fetch request with sortDescriptors. However the data is NEVER sorted. I've been pounding my head on this for several hours now.
I get the expected data in the array but it's not sorted at all. Anyone have any ideas where I am going wrong?
// Elsewhere in code
...
_charts = [[NSArrayController alloc] init];
_charts.entityName = #"Charts";
...
// When Cored Data and Managed Object Context is ready
-(void)mangagedObjectContextReady
{
NSManagedObjectContext *moc = ((AppDelegate *)[NSApp delegate]).managedObjectContext;
_charts.managedObjectContext = moc;
_charts.usesLazyFetching = NO;
_charts.automaticallyPreparesContent = YES;
_charts.automaticallyRearrangesObjects = YES;
// Create fetch request for data
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.entity = [NSEntityDescription entityForName:#"Charts" inManagedObjectContext:moc];
// Create the sort descriptors for the Charts entity
// Name and chartType are properties on the entity "Charts"
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES selector:#selector(caseInsensitiveCompare:)];
NSSortDescriptor *chartTypeDescriptor = [[NSSortDescriptor alloc] initWithKey:#"chartType" ascending:YES selector:#selector(caseInsensitiveCompare:)];
fetchRequest.sortDescriptors = #[nameDescriptor, chartTypeDescriptor];
NSError *error = nil;
BOOL success = [_charts fetchWithRequest:fetchRequest merge:NO error:&error];
if(!success)
NSLog(#"Error %#:", [error localizedDescription]);
else {
[_charts rearrangeObjects];
[_tv reloadData];
}
I use this method to get an array or sorted objects.. but data is not sorted as per above sort descriptors?
[_charts.arrangedObjects objectAtIndex:row]
_charts.sortDescriptors = #[nameDescriptor, chartTypeDescriptor];

Use data from two (or three) entities in tableview

I have an app that stores information for golf rounds. I have three Entities that I am persisting data to: Rounds, Courses, and Tees. I structured the schema in this way because there is a two-many relationship between Rounds and Courses, and a Course can have multiple Tees (blue, white, gold, etc.)
I have a UITableview that I would like to display the results of each round in. However, I would like to display data from the Rounds Entity as well as the Courses Entity. Ideally I would also like to display the Tee for that round as well,but it's not a priority.
My question is, how do I use a FetchResultsController to get data from the three entities and display it in a single cell of a UITableview?
Here is how I am saving the data to the Entities:
HandicapAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext* context = [appDelegate managedObjectContext];
NSEntityDescription *roundsEntity = [NSEntityDescription entityForName:#"Rounds" inManagedObjectContext:context];
NSFetchRequest *request =[[NSFetchRequest alloc]init];
[request setEntity:roundsEntity];
Rounds * rounds = [NSEntityDescription insertNewObjectForEntityForName:#"Rounds" inManagedObjectContext:context];
[rounds setValue:score forKey:#"roundScore"];
[rounds setValue:date forKey:#"roundDate"];
[rounds setValue:differential forKey:#"roundDifferential"];
Courses * courses = [NSEntityDescription insertNewObjectForEntityForName:#"Courses" inManagedObjectContext:context];
[courses setValue:rating forKey:#"courseRating"];
[courses setValue:slope forKey:#"courseSlope"];
[courses setValue:courseName forKey:#"courseName"];
rounds.courses = courses;
Tee * tee = [NSEntityDescription insertNewObjectForEntityForName:#"Tee" inManagedObjectContext:context];
[tee setValue:teeColor forKey:#"teeColor"];
courses.tees = tee;
NSError *error;
[context save:&error];
And then this is my FetchedResultsController
if (_fetchedResultsController != nil)
{
return _fetchedResultsController;
}
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.entity = [NSEntityDescription entityForName:#"Rounds" inManagedObjectContext:self.managedObjectContext];
// Set the batch size
[fetchRequest setFetchBatchSize:20];
// Set the sort descriptor
NSSortDescriptor * date = [[NSSortDescriptor alloc] initWithKey: #"roundDate"
ascending: NO];
NSArray * sortDescriptors = [NSArray arrayWithObjects: date, nil];
fetchRequest.sortDescriptors = sortDescriptors;
// Initialize fetched results controller - creates cache
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest: fetchRequest
managedObjectContext: self.managedObjectContext
sectionNameKeyPath: nil
cacheName: #"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
// handle errors
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _fetchedResultsController;
How do I fetch the course name and tee (this will be the tee color) for the round in the tableview cell?
Thanks!!
Just follow the relationships. If you've got a one-to-many relationship between rounds and courses, you'd need to have a relationship on courses like rounds and the inverse relationship on rounds like course. So, if you've generated subclasses for your entities, you'd access the course name like this:
NSString *courseName = round.course.name;

Fetch update in Cocoa

this is the code in my AppDelegate.m:
-(IBAction)fetch:(id)sender{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Foo" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"title == 'some title'"];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {NSLog(#"Error: %#", error);}
NSMutableArray *fooArray = [[NSMutableArray alloc]init];
for (Foo *f in fetchedObjects) {
//here another fastenum for a to-many relationship
for(Bar *b in f.relationship){
[fooArray addObject:b.title];
}
}
Everytime I perform the fetch action, even if I've changed the app.storedata file via UI and checked the changes in finder, the result is always the same until i quit the application. After a restart, the fetch result is up to date and aligned with the app.storedata file. The fooArray count is always the same, regardless if I add some entries in the entities and coredata save everything.
I've tried with [fetchRequest setIncludesPendingChanges:YES] but it doesn't affect the behaviour.
How to update the fetch result while the app is running?
UPDATE: i've "solved" the problem with this workaround:
-(IBACTION)fetch:(id)sender{
_managedObjectContext = nil;
_persistenStoreCoordinator = nil;
//rest of the code...
Is this workaround a final solution? Is there a more "correct" way to solve this problem?

Xcode - filter an NSFetchRequest and select each object

I am trying to filter a fetchRequest.
I'm at the point where the result is loaded into an NSArray.
However, I need to parse the array to pull out the individual items - right now, they look as if they were one object.
The code I'm using to get to this point is:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *moc = coreDataController.mainThreadContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Category" inManagedObjectContext:moc];
[request setEntity:entity];
// Order the events by name.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
[request setSortDescriptors:#[sortDescriptor]];
// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSArray *categories = [[moc executeFetchRequest:request error:&error] mutableCopy];
if (categories == nil) {
NSLog(#"bugger");
}
NSObject *value = nil;
value = [categories valueForKeyPath:#"name"];
This results as follows:
value = (
)
[DetailViewController loadPickerArray]
[AppDelegate loadPickerArray]
value = (
"Cat Two",
"Cat Three",
"Cat One",
"Cat Four"
)
Also, please note that the first time this ran, there were no results. I get that about 50% of the time.
Thanks for any help.
There are several methods you can filter your data.
The preferred way is to use a predicate for your search. This will give you the best performance.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *moc = coreDataController.mainThreadContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Category" inManagedObjectContext:moc];
[request setEntity:entity];
// Order the events by name.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name CONTAINS[CD] %#", #"Cat"]; //This will return all objects that contain 'cat' in their name property.
[request setPredicate:predicate];
[request setSortDescriptors:#[sortDescriptor]];
// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSArray *categories = [moc executeFetchRequest:request error:&error];
if (categories == nil) {
NSLog(#"bugger");
}
//Here you have the objects you want in categories.
for(Category *category in categories)
{
NSLog(#"Category name: %#", category.name);
}
If you wish to filter using an array, the following is possible also:
NSMutableArray *categories = [[moc executeFetchRequest:request error:&error] mutableCopy];
[categories filterUsingPredicate:[NSPredicate predicateWithFormat:[NSPredicate predicateWithFormat:#"name CONTAINS[CD] %#", #"Cat"]]
//Now, the only objects left in categories will be the ones with "cat" in their name property.
I recommend reading the Predicates Programming Guide, as predicates are very powerful, and it is much more efficient to filter your results in the store.

Request with CoreData

Here is my problem :
My CoreData model have two entity : Players and Results. The important properties of Players are :
- ratingTypePlayer, which is a String.
- resultsPlayer which is a Too-Many Relationship with Results as Destination. The Inverse relationship is playerResult.
I wish to obtain an array with all the Results of the Players which ratingTypePlayer is equal to "Toto". I don't find this kind of example.
Thanks a lot
You mean, like a fetch request?
NSManagedObjectContext *context = [[NSApp delegate] managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:#"Player" inManagedObjectContext:context]];
[request setPredicate:[NSPredicate predicateWithFormat:#"ratingTypePlayer == %#", #"Toto"]];
NSArray *players = [context executeFetchRequest:request error:nil];
If you wanted an array of the "resultsPlayer" relationships, you could do:
NSArray *results = [players valueForKey:#"resultsPlayer"];

Resources