Reputation: 4290
This is a simple question, however one that I cannot find the answer to.
I'm building an app that stores data on Projects and People, which is stored within a SQLite database using Core Data.
A project can have many people, however a person is only assigned to one project. I'm displaying the data in a Table View, which at the moment displays ALL the people stored in a database whenever you view any project - this is not ideal.
I would like to only display those people who are part of that project. How would I go about this programatically? is this done using filtering? for example:
- (void)setupFetchedResultsController
{
// 1 - Decide what Entity you want
NSString *entityName = @"People"; // Put your entity name here
NSLog(@"Setting up a Fetched Results Controller for the Entity named %@", entityName);
// 2 - Request that Entity
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
// 3 - Filter it if you want
//request.predicate = [NSPredicate predicateWithFormat:@"people.name = someones name"];
// 4 - Sort it if you want
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"lastName"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)]];
// 5 - Fetch it
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self performFetch];
}
Upvotes: 0
Views: 225
Reputation: 5960
You need a predicate, which acts as a filter. See the docs on NSPredicate.
The predicate must refer to the project you are interested in. From the small amount of code that you have shown, you might try something like this (the details depend on your own implementation).
request.predicate = [NSPredicate predicateWithFormat:@"people.project = %@", projectName"];
Upvotes: 1
Reputation: 6478
First of all, I will assume your storing routine is correct and you are setting up your relationship correctly.
Second of all, if you want to be fetching people in a specific project, the easiest way to do it might be to set up project as the entity for the fetch.
That way all you have to do is set up your predicate for the desired project, and from that managed object you should have an NSSet for the people within that project. From that set it is up to you how you want to handle the information.
Upvotes: 1