Reputation: 49
Two days I have been trying to filter the CoreData and I'm still stuck. This is my model:
Users < --- >> Sessions
I managed to create the relationship between a new session and a specific user. I also managed to get the list of all the users to display them in a tableview by this code :
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *usersDescription= [NSEntityDescription entityForName:@"Users" inManagedObjectContext:_managedObjectContext];
[request setEntity:usersDescription];
NSError *error = nil;
NSMutableArray *mutableFetchresults = [[_managedObjectContext executeFetchRequest:request error:&error]mutableCopy];
if(mutableFetchresults == nil) {
//handle error
}
usernameDataMutableArray = [[NSMutableArray alloc]init];
for (int i = 0; i< [mutableFetchresults count]; i++)
{ Users* users = (Users *) [mutableFetchresults objectAtIndex:i];
[usernameDataMutableArray insertObject: [users username] atIndex:i];
}
Now when I touch a cell called "Username1", I display a new tableView. I would like display in this tableView all the Username1 sessions.
So my question is: how can I filter all my sessions to retrieve these belong to Username1?
Upvotes: 0
Views: 512
Reputation: 46718
There is no filter required.
When you push the new view controller you hand off the instance of Users
that was selected. Then in the new view controller you ask the instance of Users
for the Sessions
instances that are associated with it.
NSSet *sessionsSet = [myUser valueForKey:@"sessions"];
You can also use a property if you have subclasses set up.
This is the point of Core Data. It is an object graph and relationships are properties on the object instance. Just call the appropriate method.
I would strongly suggest reading a book on Core Data as it will clear up a lot of the issues you are having with these fundamental concepts.
Entities should not be named in the plural. Your entities should be called User
and Session
instead of their plural form. The name of the relationship that points to a to-many should be plural and the name that points to the to-one should be singular. This helps greatly with code clarity and maintainability. Plural tends to indicate a collection of objects instead of a single object like you have now.
Upvotes: 2