IOS uses global data for view controllers

I used the application delegate as a "global bucket" to exchange data between different view controllers. Usually I do something like this:

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

And then, I will store the data in appDelegate and collect data from appDelegate with another view controller. Somehow, this seems awkward and inappropriate (although it does work).

Is there a better way? Can I configure the “listener” on some global shared area, if someone inserts a data element there, another object will receive a “call back” to tell him that someone has data ready for him?

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

+7
source share
1 answer

A clean, although not necessarily different, way to do this is to create a singleton class, for example. AppData , which you can access in various ways and which will be available to all your other classes. It has the advantage of separating your applications from specific applications from application delegation applications. You can define a class as follows:

  @interface AppData: NSObject

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

 @end

It is common practice to define class methods for such a class for access, for example, parameter values ​​or application-specific constants or other singleton objects. There are many possibilities.

In the end, you can do a lot with just the methods of the class, which you would call something like [AppData theMethod] . Just remember if there is self to access inside the class method.

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

I'm not sure that I would call this approach "best practice", but I found this template quite convenient.

+3
source

All Articles