views:

243

answers:

1

When programming for the iPhone, I find that I often need to use the same instance of an object in multiple views. What is the best way to handle this? My strategy so far has been to create it as a member of the root view and pass it to subsequent views which retain it as a member. However, this does not seem like a very good approach since it would be very difficult to update what the reference in each class is pointing to. I have also seen singleton classes as well as the AppDelegate used for this purpose. As an iPhone developer, how do you handle this problem in large apps?

+2  A: 

The App Delegate approach is easy to do, the downside is that everything has to go fetch the delegate and then get the shared object.

Singletons mean only classes using the singleton have to know about it, but can be harder to write unit tests against or clean up properly in low memory situations. Also you must write the singleton classes more carefully so they work correctly (look at Apple docs on singletons).

Passing an object around can get old because sometimes you end up only having a link to the object to pass to someone else, so I would avoid that approach unless you were just passing from one parent to a few immediate children.

Between the first two, I lean a little towards singletons just because of the dependency graph being simpler (as mentioned classes only including singleton headers they care about instead of a whole bunch from the App Delegate). If you had a number of them the thing to do would be to make singleton distribution classes that held onto single instances of groups of classes, just to keep the app delegate lighter and not to have to make so many classes that were true singletons.

I do like using the app delegate to hold on to the root of your actual UI, like the tab bar controller or primary view controller. That just seems more natural than stuffing it elsewhere.

Kendall Helmstetter Gelner