How to easily pass data between Views in iOS

When I first started developing for iOS, one huge problem I encountered was how to easily pass and keep data between view controllers without having to save the data to a database of some sort and/or use nsuserdefaults. One way of doing this easily would be using a shared instance of a class that contains the information you want to save.

Here is a link to my github repo of the code:

Basically, you add a method called shared instance to your class that will “store” the information. In this case a class called DataStorageController will be used to hold the values entered on the first screen and pass them to the third view we see.

The method we use to do this shared instance is this:

+(id) sharedInstance 
    static id sharedInstance = nil;
        if (sharedInstance == nil) {
            sharedInstance = [[self alloc] init];
   return sharedInstance;

//and when you allocate a new instance in another view controller do this

DataStorageController *dataClass = [DataStorageController sharedInstance];

5 thoughts on “How to easily pass data between Views in iOS

  1. Hey andrew, in case you were wondering this design pattern is a singleton pattern and the class you’re creating is called a singleton. The method is used in a lot of different languages but you pretty much can’t live without them in objective-C due to the lack of true global variables. Just thought you might want to know in case you needed to find more info about it and didn’t know what keyword to use.

  2. The problem with this sort of thing is that your singleton is very inflexible. Also, singletons are “by design” supposed to be reflective of some global application state data rather than data that applies to a very specific moment in the execution of the application. Have you considered simply passing NSDictionarys, Andrew? I’ve seen them used quite a bit in projects that don’t use Core Data.

  3. Pingback: Making Network Calls in iOS | Andrew Rauh

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s