Core Data to-many relationship in code
Posted
by
Jan Bezemer
on Stack Overflow
See other posts from Stack Overflow
or by Jan Bezemer
Published on 2012-12-15T05:02:16Z
Indexed on
2012/12/15
5:03 UTC
Read the original article
Hit count: 143
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;
//sessie.users = 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: %@", info.name);
NSLog(@"Having problems with this: %@",info.user);
//User *details = info.user;
//NSLog(@"User: %@", details.age);
}
© Stack Overflow or respective owner