Question

My application downloads photos from web server. Is downloading photo information from server Controller's business or data's business? I mean should I download data in controller class

Photo.title = [self getPhotoInfoFromServer: url]; 

or in data class?

[Photo getPhotoInfoFromServer: url];
Was it helpful?

Solution

Global point of view

An UIViewController is here to Control a View. It means interactions (give good data to the view, and answer to view interactions).

A model / an entity can be created by independents sources (unless the source itself is semantically linked with your model). A Photo is a Photo, whatever if created from a data retrieved from a server or from a local Camera Roll picture.

You should use a custom DataFetcherController to get a remote data and transform it into a instance.

Example Flow

Your UIViewController subclass needs a list of photos. It asks the PhotoServerFetcherController for getting the data from the Server. The fetcher can look into its cache and perfom a request the a server if needed. When the PhotoServerFetcherController get the data and parse it to instances of your Photo entity and give it back to the UIViewController`.

Data fetcher interactions

The best is to create your own FetcherControllerinterface (@protocol keyword). You can handle 2 async callbacks : success with the data in it and failure with the error in it (connection ? bad input ?).

Here you have many ways to implements that, the main 2 patterns for 1 to 1 interactions are delegate or block callbacks.

OTHER TIPS

You should download the photos in to data class then the viewControllers those needs that data can easily get from data class. Actually you should follow MVC where

M= Modal (Your Data Class)

C= Controller class

V= view what your controller displays

I prefer using a dedicated server class, which instantiates models, and is used from the controller: [photoServer getPhotoFromURL:URL], or [photoServer getPhotoFromURL:URL completion:^(Photo *photo, NSError *error){...}]

Why a dedicated server class?

  • photos may come from several sources, and you don't want to write many +[Photo getPhotoFrom...] methods and hinder the reusability and maintainability of your Photo class.
  • Whenever the server implementation changes, you just have to modify a single class, the class which is responsible for the server. The Photo model remains unaware there is even a server, and is not concerned by the server implementation. This is the principle of single responsibility in action.

Why should this code be called from the controller?

  • server access is inherently asynchronous, and may fail. Only controllers know how to deal with delay and errors when we talk about user feedback.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top