I have three entities: Session, User and Test. A session has 0-many users and a user can perform 0-6 tests. (I say 0 but in the real application always at least 1 is required, at least 1 user for a session and at least 1 test for a user. But I say 0 to express an empty start.) All entities have their own specific data attributes too. A user has a name, A session has a name, a test has six values to be filled in by the user, and so on. But my issue is with the relationships.
-
How do I set multiple users and have them added to one session (same goes for multiple tests for one user).
-
How do I show the content in a right way? How do I show a session that has multiple users and these users having completed multiple tests?
Here’s my code so far with regard to issue 1:
Session *session = [NSEntityDescription insertNewObjectForEntityForName:@"Session"
inManagedObjectContext:context];
session.name = @"Session 1";
User *users = [NSEntityDescription insertNewObjectForEntityForName:@"User"
inManagedObjectContext:context];
users.age = [NSNumber numberWithInt:28];
users.session = session;
//session.user = users;
[sessie addUserObject:users];
With regard to issue 2: I can log the session, but I can’t get the user(s) logged from a session.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (Session *info in fetchedObjects) {
NSLog(@"Name of session: %@", info.name);
NSLog(@"Having problems with this: %@",info.user);
//User *details = info.user;
//NSLog(@"User: %@", details.age);
}
I find it useful (and it seems to be common practice from the code samples that I saw at SO), to use the plural form for to-many relationships, e.g.
usersfor the to-many relationship from Session to User. It emphasizes the fact that the value of the relationship is a set and not a single object, and might make things a bit clearer.So your model would look like this:
Issue 1: If you have created a
Session *sessionand aUser *user, thenadds the user to the session. Calling
has the same effect. But only one of these calls is required, it automatically implies the other, if the relationships are properly defined as inverse relationships.
Issue 2: For a
Session *session,session.usersis the set of all users related to that session. It is aNSSetand you can iterate through that set. Similarly,user.testsis the set of all tests for a user.So the following code displays all sessions with their users and tests: