I have 2 core data entities: Question, and QuestionType. Every Question has exactly 1 QuestionType.
QuestionType has a typeName string attribute; which is primarily how I identify which QuestionType it is. It is fixed to a list of a few different types. I am wondering if it is possible to use the list of all the QuestionTypes in the data as an enum, or if not, what’s the best way to use this list to assign a QuestionType to a Question, and check the QuestionType later?
Currently, when I want to assign a type to a question (based on knowing the typeName), I am doing this:
NSFetchRequest *questionTypeFetchRequest = [[NSFetchRequest alloc] init];
questionTypeFetchRequest.entity = [NSEntityDescription entityForName:@"QuestionType" inManagedObjectContext:self.managedObjectContext];
NSPredicate *questionTypePredicate = [NSPredicate predicateWithFormat:@"typeName like %@", [questionData objectForKey:@"questionType"]];
questionTypeFetchRequest.predicate = questionTypePredicate;
question.questionType = [[self.managedObjectContext executeFetchRequest:questionTypeFetchRequest error:&error] objectAtIndex:0];
This seems like a lot of work just to assign a QuestionType to my Question! And I have to repeat this for other similar entities.
And then when I want to check the QuestionType later, I am doing:
if ([question.questionType.typeName isEqualToString:@"text"]){
This works fine, but I feel like I should be comparing the question.questionType to the specific QuestionType I am looking for, as opposed to just comparing the typeName.
Is there any way to set up an enum to hold my QuestionTypes, so that I can do this:
question.questionType = Text;
switch(question.questionType)
{
case Text:
Does
questionTypehave to be an object? If you want to use an enum, you can just declare yourquestionTypeproperty of theQuestionentity to be an integer, not another entity likeQuestionType.Or, you can declare your
questionTypeproperty to be a string, and directly keeptypeNamethere.Even when you use an enum, the syntax is not like
EnumName.EnumKindin C / Objective-C. See any textbook for the syntax.If you keep using
questionTypeas an entity, I would suggest you to cache the results of the fetch in the dictionary, as in:and something like that.