1

I have a UITabBarController, and all the VCs in the tabs use the same model (each tab just displays the model differently). How do I create this model and share it amongst the other VCs? Do I initialize it in the landing VC (when the user opens the app) and then pass it to the others using prepareForSegue or something? Or is there another way to create a "shared" model/class between VCs in an app?

Tony Stark
  • 24,588
  • 41
  • 96
  • 113

2 Answers2

2

you have 3 methods basically.

1st: use your AppDelegate to store a model and access it with:

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.model

2nd: you can use a singleton (a shared instance):

Tutorial: http://www.galloway.me.uk/tutorials/singleton-classes/

3rd: use a factory class that creates your tabbar share the same model to all controlles and returns it to your appDelegate.

zoul made a great sampleProject to illustrate how that works: https://github.com/zoul/Singletons-Suck

the 3rd is my favorite =)

mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
Sebastian Flückiger
  • 5,525
  • 8
  • 33
  • 69
0

you could initialize it in your AppDelegate as class property and call it from everywhere:

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.myModel....