Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

saving data in swift in app with multiple views

I am trying to build an app in swift with multiple views (4). In the courses all the apps have only 2 views and i wasnt sure how i can save data from say the first view and then still have available and saved it in the 3rd and 4th views? I know it is something to do with having a data model etc but i have been finding it very confusing Thanks for any help you can give it is greatly appreciated.

1 Answer

Michael Reining
Michael Reining
10,101 Points

Hi Leo,

There are many possible answers to your question.

Here are two ways to send data along.

Let's say you have an object in view 1 and you would like to update it in view 4.

You could always pass this object along in the prepare for segue method. So the moment the user switches from view 1 to view 4, you are making sure that you have the object in the view controller of view 4. Since classes are copied by reference, the new view is still pointing at the same object / updating the same instance.

http://stackoverflow.com/questions/27364117/is-swift-pass-by-value-or-pass-by-reference

Another way would be to use a singleton. That can be done if you only want one instance of an object in the entire app. This way you don't have to pass around the object in the prepare for segue method since there can only be one. However, I would probably first use the above approach since singletons have some other disadvantages.

I hope that helps a little,

Mike

PS: Thanks to the awesome resources on Team Treehouse, I launched my first app.

Now you can practice writing Swift code directly on your iPhone :-)

Code! Learn how to program with Swift