0

I have an entity which has attributes that get populated from 5 view controllers.

The app is basically a detailed form based questionnaire with 5 questions and each of the 5 view controllers consists of one question and its set of answer choices. In the first 4, user has multiple choice questions. In the last question user can choose multiple values from the set of options.

I have maintained an entity each for each view controller for the options to be displayed for that view controller.

To capture user's answers, I have created an entity named Answer with string attributes for answer for first 4 questions and a relationship with fifth entity so that I can capture set of answer choices selected by user for 5th question.

I also need to save user selections as and when user moves on from 1st question to 2nd to 3rd and so on and not in one go when user has answered all the questions.

Also, user can discard answers if he pops the first question's screen.

What is the best possible way to achieve it?

I was looking for the following options -

  1. Create an Answer entity record before coming to the first question view controller. Also a managed object context (moc) too. I then keep a moc property in each of the 5 view controllers and then pass on the moc created before coming to first controller from the first controller to fifth controller along with the Answer managed object. Save in this moc whenever user moves from one question to next.
  2. Create a DataCollector type of Singleton class where I have an init method to create Answer entity record and methods for creating moc and saving to moc. Then from each question I refer to this Answer managed object and also share the same moc.

Please advice.

letsbondiway
  • 470
  • 3
  • 18

1 Answers1

0

The easiest way I can see to do this is to just transfer all of the answers along the way into the next view controller using the prepare(for segue:) method. You would do this by saying

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let secondScene = segue.destination as! (nextController)
        secondScene.answerQuestion1(declared variable in nextController) = (value you are transferring)
        }

When you move to the next UIView, in the view controller, after the class declaration you can simply declare the variable you want to store the value in, so for the UIView corresponding to the next question,

class QuestionTwo: UIViewController {

    var answerQuestion1

    override func viewDidLoad() {
        super.viewDidLoad()

Repeat this for all of the view controllers, and by the time you are at the 5th, you will have all of the answers to the first 4 questions as well as the 5th, at which point you can save it in CoreData and then clear the values from the variables.

E. Chen
  • 11
  • 5