cannyboy
cannyboy

Reputation: 24406

Creating Core Data relationships after filling up entities with data

Say you have a couple of Core Data entities .. Student and Exam. These two are initially filled with data from two xml files downloaded from the web.

Now, Students and Exams are separate things... initially there are no connections between them. But after filling out these two entities, I might want to connect certain students to certain exams. Or I might want make all students take a particular exam. But I still want to be able to treat Exams as independent things, which might have no students connected.

I'm unsure how to do this with Core Data. In the data model, you either have a relationship or yo don't. Should I have two different entities for Exam... one for independent exams, and one connected to the student which can be built up from the other Exam enitity?

Upvotes: 2

Views: 1143

Answers (2)

David
David

Reputation: 7303

I think you should have a relationship between the two entities (exam and student) but mark it as optional.

Upvotes: 2

David Gelhar
David Gelhar

Reputation: 27900

No, you should not make two entity types.

Just because you have a relationship between two kinds of entities doesn't mean you can't create an object where that relationship is nil.

So, assuming you have a many-to-many relationship between Student and Exam, you might create a new exam by doing something like:

Exam *newExam = [NSEntityDescription
     insertNewObjectForEntityForName:@"Exam"
     inManagedObjectContext:context];
newExam.course = @"CS 101";
newExam.description = @"Midterm";

You might then later establish a relationship between a student and that exam like:

[newExam.students addObject:aStudent];

(where students is the name of the relationship between Exam and Student

Upvotes: 7

Related Questions