Austin Berenyi
Austin Berenyi

Reputation: 1053

How do I save values from the child view controllers of a UIPageViewController to use elsewhere in an app?

I have a UIPageViewController containing multiple view controllers each with questions for the user to respond to. Once these questions are answered I want to save the values somewhere locally so I can later create a PDF populated with these values. What is the best way to do this? Would I use NSUserDefaults?

Upvotes: 0

Views: 47

Answers (1)

slushy
slushy

Reputation: 12385

It depends on how you want the data to persist. If you want the data to persist the life of the user, even if the app is deleted from the device, you would obviously need to store it away from the client such as in a database (i.e. Realm, CoreData). If you want the data to persist the life of the app itself, data that you would continue to use to shape the user's experience, you could use UserDefaults but that doesn't seem like what you're trying to do. And if you just want the data to persist the life of that instance of the app, store it in regular properties.

I suspect, for whatever reason, the third option would be your choice. If so, I would suggest creating a model object that's as an instance property of the parent view controller (that all page view controllers can reference)...

class SurveyAnswers {

    var userName: String?
    var userAge: Int?
    var favoriteSauce: PizzaSauce?
    var livesWithCats: Bool?

}

...and simply use the protocol/delegate pattern to pass data from the child to the parent which would update properties in that object (so long as they are updating the same instance of that object). Then, when you're ready to prepare the PDF file, simply ask the parent for that object, whose properties have been set by the child view controllers.

And if you're OK with it, you could use the shared AppDelegate as a way to store and retrieve this data. I would just caution against making this a habit but depending on your application as a whole, this may be a perfectly acceptable option.

General rule of thumb: set properties in destination objects to pass data forward and use delegates to pass data backward.

Upvotes: 1

Related Questions