views:

307

answers:

2

Been researching how to send data from one child view to another child view. The application has several views, where one is kind of real-time Settings view. Changes in settings should effect stuff inside other views.

NSUserDefaults seems to be popular, but I don't want persistent data nor automatic saving into database/file. Looks like potential slowdown, which I want to avoid.

Second popular thing is passing a reference to some common top level object into each child view. Just haven't found any tutorial, which would show me in detail how to do this... Most likely so easy, no tutorial is needed - after you figure it out once! Would appreciate, if you can point me to right direction (URL)!

Question: I'm thinking about using one "singleton object" to store "global data", access it from everywhere anytime. What could wrong with this? If I create it at e.g. appDelegate.m it should exist before anyone tries to access it, right?

I'm looking at this sample code.

A: 

The beauty of a singleton is that it is automatically created when you first access it via some [singletonClass sharedInstance]. So you don't need to "create" it while launching. If it is global data that needs to be accessed from any view singleton might be the right way of doing this.

Felix
Do you, or anybody else, know of another way to do this? I mean, the singleton is pretty rad and everything, but is it the only way to deal with this situation?
Kenny Winker
Why is this rad? If you need the singleton to exist in memory once for the duration of the application? you can dealloc it when the app closes.
Felix
+1  A: 

I would recommend using delegates and/or notifications.

Instead of creating a new singleton in the app delegate, add the necessary data (or, even better, references to the data) in the app delegate and have the views have references to the app delegate.

You can also set up notifications so that your views can keep track of changes to the data that they display.

gerry3
Notifications to changed data look useful, thanx! Will use those at some point, familiar from other environments.Delegates on the other hand... seem to be recommended pattern in iPhones, but haven't found yet any good tutorial (with sample code). I still have to package data inside own class and/or add into appDelegate. Singleton object seems to offer same result with less code, less chances for bugs.
JOM
I don't really see a big difference in terms of code or chances for bugs. I would argue that almost any tutorial or sample code is using delegates (just look at the list of protocols behind the @interface declaration of the app delegate and/or view controllers).
gerry3