darksky
darksky

Reputation: 21019

Delegates and Notifications in Objective-C

In my AppDelegate, I download some data from a JSON feed. I am downloading a now/next/later schedule for a few channels. I have three different view controllers for each now, next and later. In each view controller, a user can add/remove the channels so when that happens, the newly added channel data has to be downloaded again.

Since the data is downloaded in the AppDelegate and stored there, how would I pass it to the three view controllers? Should I implement three separate delegates? Keep in mind that when adding a new channel, its data has to be downloaded again (which I am doing outside the AppDelegate now).

Any help please?

Thanks

Upvotes: 1

Views: 387

Answers (2)

Toastor
Toastor

Reputation: 8990

This is basically a matter of style and your approach isn't invalid as such.

I'd do it another way, though - the AppDelegate is not meant to be used as a workhorse and having several AppDelegates at the same time is simply impossible.

Here are some thoughts about how this could be done (though it's of course not the only proper way):

  • First, I'd employ Core Data or some other sort of storage which is available from anywhere within your app.
  • Then maybe I'd introduce some sort of "data controller" class (maybe a singleton). This class should handle both download of data and the distribution of that data to your viewcontrollers as requested.
  • By having one central controller for that purpose, you'd ensure that data gets downloaded only once because the controller knows exactly which data is already in stock.
  • Your viewcontrollers would neither be responsible for managing downloads anymore nor would they access the data on disk by themselves. They'd just make a request to your data controller and get a callback when the requested data is available - no matter if it was on disk already or has been downloaded for the occasion.
  • This keeps your VCs slim and focused and reduces the pain of making changes to your interface.

Upvotes: 1

Jano
Jano

Reputation: 63667

Toastor's answer is correct and as he says, there are several ways to do this. One is to call a data access class and change the values OR listen for changes on the values. For the later, the Key-Value Observing Programming Guide says the following:

KVO is particularly useful for communication between model and controller layers in an application.

  • A controller object typically observes properties of model objects, and a view object observes properties of model objects through a controller.
  • In addition, however, a model object may observe other model objects (usually to determine when a dependent value changes) or even itself (again to determine when a dependent value changes).

Another is to make the dependency explicit, maybe passing a data access class saved in your app delegate. See Object-oriented design question, iPhone.

Upvotes: 1

Related Questions