Creating Core Data relationships after filling up entities with data
Say you have a couple of Core Data entities .. Stud开发者_开发技巧ent 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?
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
I think you should have a relationship between the two entities (exam and student) but mark it as optional.
精彩评论