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: https://github.com/andrewrauh/SharedInstanceDemo
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];
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.
An update for iOS 5 and GCD
http://lukeredpath.co.uk/blog/a-note-on-objective-c-singletons.html
Nice to meet you last night! Hope the LinkedIn stalking didn’t freak you out too much. 🙂 – JC
no problem! feel free to follow me on twitter/facebook as well
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.
Pingback: Making Network Calls in iOS | Andrew Rauh