7

I have been using app delegate as a "global bucket" to share data between various view controllers. Typically I do something like this:

My_AppDelegate *appDelegate = (My_AppDelegate *)[[UIApplication sharedApplication] delegate];

And then, I would stick data into the appDelegate, and pick up data from the appDelegate with another view controller. Somehow, this seems clumsy and inappropriate (although it does work).

Is there a better way? Can I set-up a "listener" on some kind of a global sharing area, if somebody sticks a data element in there, another object would get a 'call-back' to let it know that somebody has data ready for it?

In Java we used to do this with Observer/Observable class - maybe there is something like this, or better in iOS?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
geekyaleks
  • 1,281
  • 3
  • 18
  • 29

1 Answers1

3

A cleaner, although not necessarily different, way to do this is to create a singleton class, e.g. AppData, which you can access in a variety of ways, and which would be available to all your other classes. It has the benefit of separating your app-specific stuff from the app delegate stuff. You might define the class this way:

@interface AppData : NSObject

// Perhaps you'll declare some class methods here...

@end

A common thing I do is define class methods on such a class to access, for example, settings values, or app-specific constants or other singleton objects. There are a lot of possibilities.

In the end, you can get a lot done with just class methods, that you would call something like [AppData theMethod]. Just remember there's no self to access inside a class method.

Taking it one step further, you can define ivars for the AppData class, and then manage a singleton instance of AppData. Use a class method, e.g. +sharedInstance, to get a handle to the singleton on which you could then call mehods. For example, [[AppData sharedInstance] someMethod:myArgument]. Your implementation of +sharedInstance can be where you manage the actual creation of the singleton, which the method ultimately returns.

I am not sure if I'd call this approach a "best practice", but I've found this pattern quite handy.

Mark Granoff
  • 16,878
  • 2
  • 59
  • 61