Question

I'm making an iOS app with different types of quizzes, with all the questions and answer choices stored in CoreData.

I created two entities, one called QuestionData that has attributes such as 'question' 'answer1' (meaning, answer choice 1), 'answer2' etc, and then another entity called Quiz, with attributes like 'name' and 'quizId' and I created a to-many relationship on Quiz called 'dataData' that will refer to all the questions/answers etc.

When I created some test data (to experiment with the relationships), I first created the questionData, then set the name and id for the Quiz, and then I tried to set the data in the relationship like this,

[quizInfo setValue:questionData forKey:@"quizData"];

Which was supposed to store/set all the questions/answers in the quizData key of the Quiz entity. However, I got this unacceptable type error, telling me that it 'desired' an NSSet, but i instead gave it a type of QuestionData.

'NSInvalidArgumentException', reason: 'Unacceptable type of value for to-many relationship: property = "quizData"; desired type = NSSet; given type = QuestionData; value = <QuestionData: 0x89447a0> (entity: QuestionData; id: 0x8919900 <x-coredata:///QuestionData/t6B583F60-5794-47FA-8A51-

I understand the concept of a 'set' however, I'm not sure how I can make questionData a set when it comes time to do this

[quizInfo setValue:questionData forKey:@"quizData"];

Full code:

 NSManagedObjectContext *context = [self managedObjectContext];
    QuestionData *questionData = [NSEntityDescription
                                 insertNewObjectForEntityForName:@"Questiondata"
                                 inManagedObjectContext:context];
    [questionData setValue:@"do you like big basketballs" forKey:@"question"];
    [questionData setValue:@"yes" forKey:@"answer1"];
    [questionData setValue:@"no" forKey:@"answer2"];
    [questionData setValue:@"maybe" forKey:@"answer3"];
    [questionData setValue:@"maybe" forKey:@"correctAnswer"];

    Quiz *quizInfo = [NSEntityDescription
                                  insertNewObjectForEntityForName:@"Quiz"
                                  inManagedObjectContext:context];
    [quizInfo setValue:@"1" forKey:@"quizId"];
    [quizInfo setValue:@"sportsquiz" forKey:@"name"];
    [quizInfo setValue:questionData forKey:@"quizData"];
Was it helpful?

Solution

You need to wrap your questionData inside a set. Since you only have one question at this time you can use

[quizInfo setValue:[NSSet setWithObject:questionData] forKey:@"quizData"];

When you have more than one question you can either use:

[quizInfo setValue:[NSSet setWithObjects:question1Data,question2Data,question3Data,nil] forKey:@"quizData"];

Or you could put your questions into an NSMutableArray and use

[quizInfo setValue:[NSSet setWithArray:questionArray] forKey:@"quizData"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top